[SOLVED] Is there a better way than Thread.Sleep() in ASP.NET API? See scenario below

Issue

I am building a web application using ASP.NET Core Web API. It’s for SSH communication with a Linux server, so I have to wait for the server to respond. Now I am using Thread.Sleep(2000); just like the code below.
But I am sure there are better ways to do this; Maybe Task.Wait? which one I should choice for in such Web API scenario?

Thanks a lot

using System;
using Renci.SshNet;
using System.Threading;
namespace SSHTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //Connection information
            string user = "xx";
            string pass = "xx";
            string host = "uxx.ac.uk";

            using (var client = new SshClient(host, user, pass))
            {
                client.Connect();
                var cmd = client.CreateCommand("echo 123");
                var asynch = cmd.BeginExecute();
                while (!asynch.IsCompleted)
                {
                    //  Waiting for command to complete...
                    Thread.Sleep(2000);
                }
                var result = cmd.EndExecute(asynch);
                Console.WriteLine(result);
                client.Disconnect();
            }
        }
    }
}

Solution

You can use asynch.AsyncWaitHandle.WaitOne(); instead of the explicit while loop to achieve the same behavior.

Alternatively you could turn it to an awaitable Task with Task.Factory.FromAsync.

Your code would look something like this:

using System;
using Renci.SshNet;
using System.Threading;
namespace SSHTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            //Connection information
            string user = "xx";
            string pass = "xx";
            string host = "uxx.ac.uk";

            using (var client = new SshClient(host, user, pass))
            {
                client.Connect();
                var cmd = client.CreateCommand("echo 123");
                var result = await Task<string>.Factory.FromAsync(
                    cmd.BeginExecute,
                    cmd.EndExecute
                );
                Console.WriteLine(result);
                client.Disconnect();
            }
        }
    }
}

I would personally create an extension method that does this conversion and go with it since async/await is the nowadays standard approach to asynchronous programming in C#.

Fortunately there is already a nuget package that gives you just that.

Answered By – Quacke

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *