4

我在框架 3.5 上的 c# 中使用 Renci.SshNet 并在 unix 框上运行命令,如下所示。

        string host = "localhost";
        string user = "user";
        string pass = "1234";
        SshClient ssh = new SshClient(host, user, pass);


        using (var client = new SshClient(host, user, pass))
        {
            client.Connect();


            var terminal = client.RunCommand("/bin/run.sh");

            var output = terminal.Result;

            txtResult.Text = output;
            client.Disconnect();
        }

每件事都运行良好,我的问题是“有没有办法让它不等待 client.RunCommand 完成”我的 prog 不需要来自 unix 的输出,因此我不想等待 RunCommand完成。此命令需要 2 小时才能执行,因此希望避免在我的应用程序上等待时间。

4

2 回答 2

1

由于我假设 SSH.NET 没有公开真正的异步 api,您可以在线程池上排队RunCommand

public void ExecuteCommandOnThreadPool()
{
    string host = "localhost";
    string user = "user";
    string pass = "1234";

    Action runCommand = () => 
    { 
        SshClient client = new SshClient(host, user, pass);
        try 
        { 
             client.Connect();
             var terminal = client.RunCommand("/bin/run.sh");

             txtResult.Text = terminal.Result;
        } 
        finally 
        { 
             client.Disconnect();
             client.Dispose();
        } 
     };
    ThreadPool.QueueUserWorkItem(x => runCommand());
    }
}

请注意,如果您在 WPF 或 WinForms 中使用它,那么您将需要分别txtResult.Text = terminal.Result使用Dispatcher.InvokeControl.Invoke

于 2014-08-06T18:58:51.310 回答
0

关于什么

    public static string Command(string command)
    {
        var cmd = CurrentTunnel.CreateCommand(command);   //  very long list
        var asynch = cmd.BeginExecute(
            //delegate { if (Core.IsDeveloper) Console.WriteLine("Command executed: {0}", command); }, null
            );
        cmd.EndExecute(asynch);

        if (cmd.Error.HasValue())
        {
            switch (cmd.Error) {
                //case "warning: screen width 0 suboptimal.\n" => add "export COLUMNS=300;" to command 
                default: MessageBox.Show(cmd.Error); break;
            }
        }

        return cmd.Result;
    }
于 2015-04-15T07:57:11.503 回答