ssh.net c#runco​​mmand问题

时间:2014-08-06 18:43:37

标签: c# ssh.net

我在框架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();
        }

每件事情都运作良好,我的问题是“有没有办法让它不应该等待客户端。运行命令完成”我的编程不需要unix的输出,因此我不想等待为RunCommand完成。此命令需要2个小时才能执行,因此希望避免在我的应用程序上等待。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
    }