C#:等到命令完全执行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#:等到命令完全执行相关的知识,希望对你有一定的参考价值。

我试图从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();
}

以上是关于C#:等到命令完全执行的主要内容,如果未能解决你的问题,请参考以下文章

如何使python等到批处理执行完成

尝试在 C 中创建对所有人具有完全权限的文件

C++ 代码片段执行

Python 弹出命令。等到命令完成

如何让jquery在页面没加载完就可以执行,每次要等到整个hmtl加载完才可以执行jquery,这样很慢

Node.js 等到异步函数完成,然后继续执行其余代码