C#:等待命令完全执行

时间:2019-03-13 07:00:24

标签: c# ssh

从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;

        }

1 个答案:

答案 0 :(得分:1)

您可以尝试类似于以下代码的内容:

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();
}