ssh.net c# runcommand issue

atif picture atif · Aug 6, 2014 · Viewed 18k times · Source

I am using Renci.SshNet in c# on framework 3.5 and running a command on unix box like below.

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

every thing works well, my question here is that "Is there a way that it should not wait for client.RunCommand to be finish" My prog doesn't need a output from unix and hence I don't want to wait for the RunCommand to finish. This command took 2 hours to execute so wanted to avoid that wait time on my application.

Answer

Yuval Itzchakov picture Yuval Itzchakov · Aug 6, 2014

As i assume SSH.NET doesn't expose a true asynchronous api, you can queue RunCommand on the threadpool:

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

Note if you use this inside WPF or WinForms then you will need to txtResult.Text = terminal.Result with Dispatcher.Invoke or Control.Invoke, respectively.