![](/img/trans.png)
[英]how do i wait till the thread complete its job then execute the next command c#?
[英]C#: Wait till command is completely executed
從C#代碼連接到遠程Unix服務器后,我試圖執行命令提示符行。 我已經使用了下面的代碼,並且正在工作。 但是,我希望命令在執行下一個命令行之前完全執行。 當前行的執行速度更快,因此,我得到的結果是錯誤的。
每個命令應完成處理,然后移至下一個命令。 在我的C#Web應用程序中,在按鈕單擊事件上有以下代碼
SshClient sshclient = new SshClient(hostname, username, pwd);
sshclient.Connect();
ShellStream stream = sshclient.CreateShellStream("cmsd", 80, 24, 800, 600, 1024);
objclass.sendCommand("command1", stream).ToString();
objclass.sendCommand("command2", stream).ToString();
該類文件包含以下方法:
public StringBuilder sendCommand(string customCMD, ShellStream stream)
{
StringBuilder answer = new StringBuilder();
answer.Clear();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
WriteStream(customCMD, writer, stream);
answer = ReadStream(reader);
return answer;
}
private void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
{
writer.WriteLine(cmd);
while (stream.Length == 0)
{
Thread.Sleep(500);
}
}
private StringBuilder ReadStream(StreamReader reader)
{
StringBuilder result = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
result.AppendLine(line);
}
return result;
}
//嘗試新代碼
public StringBuilder sendCommand(string customCMD, ShellStream stream)
{
StringBuilder answer = new StringBuilder();
answer.Clear();
answer.Length = 0;
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
while (!stream.DataAvailable)
{
WriteStream(customCMD, writer, stream);
Thread.Sleep(5000);
}
answer = ReadStream(reader);
return answer;
}
您可以嘗試類似於以下代碼的操作:
using (var client = new SshClient(hostname, username, pwd))
{
client.Connect();
var cmd = client.CreateCommand("sleep 15s;echo 123");
var asynch = cmd.BeginExecute();
while (!asynch.IsCompleted)
{
// Waiting for command to complete...
Thread.Sleep(2000);
}
result = cmd.EndExecute(asynch);
client.Disconnect();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.