Difference between Thread.Sleep and Task.Delay

Asked

Viewed 3,990 times

8

I am developing a client/server communication, and using Task for asynchronous communication.

Previously, I had already made another communication where I used Thread, works smoothly and consumes little processing.

In that now with Task I had a high processing, and it did not seem to happen the Delay between iterations of while. I decided to change all the Task.Delay for Thread.Sleep.

And the result was satisfactory. It started to have the delay at each iteration and the CPU consumption remained low.

Here is the question: What’s the difference between Task.Delay() and Thread.Sleep()

Code snippet where a TcpListener accepts the connections (This part is within the execution of a Task):

while  (_running)
{
    if (server.Pending())
    {
        TcpClient client = server.AcceptTcpClient();
        string nIP = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
        ChatServerClient clie = new ChatServerClient(++_idControl, client, this._log);
        _clients.Add(clie);
        ClientConnected(new ClientChatEventArgs() { Client = clie });
        clie.OnClientStop += clie_OnClientStop;
        clie.StartClient();
        clie.Enviar.Enqueue("Servidor Conectado.");
    }
    else
    {
        Thread.Sleep(2000); //Funciona, baixo CPU e espera o tempo
        //Task.Delay(2000); //Não funciona, alto CPU e não espera o tempo
    }
}
  • 1

    See help: https://answall.com/q/86014/101

1 answer

5


Taking into account the following example

private void button1_Click(object sender, EventArgs e)
{
    Thread.Sleep(10000);
}

private async void button2_ClickAsync(object sender, EventArgs e)
{
    await Task.Delay(10000);
}

public static void Sleep(int millisecondsTimeout)

This is the classic way to suspend execution. This method will suspend the current segment until the amount of time has elapsed. When you call Thread.Sleep in the above way, there is nothing you can do to abort it, except wait until the time elapses or restart the application. That’s because Thread.Sleep suspends the segment that is making the call. And because I am calling Thread.Sleep in my button event handler, the user interface stays frozen until the specified time ends.

public static Task Delay(int millisecondsDelay)

Task Delay. acts in a very different way than Thread.Sleep. Basically, Task Delay. will create a task that will be completed after a delay. Task Delay. is not blocking the user interface and it will continue responding.

Behind the scenes there is a stopwatch until the specified time. Since the timer controls the delay, we can cancel the delay at any time by simply stopping the timer. To cancel the execution of Task Delay. you have to pass more parameter CancellationToken cancellationToken. The example can be as follows.

CancellationTokenSource tokenSource = new CancellationTokenSource();
private void button1_Click(object sender, EventArgs e)
{
    Thread.Sleep(10000);
}

private async void button2_ClickAsync(object sender, EventArgs e)
{
    await Task.Delay(10000, tokenSource.Token);
}

private void button3_Click(object sender, EventArgs e)
{
    tokenSource.Cancel();
}

An important detail to remember is the implementation of async in Task.Delay. That as documented, Asynchrony is essential for activities that are potentially being blocked, as well as when your application accesses the Web. Access to a web resource is sometimes slow or delayed. If such activity is blocked within a synchronous process, the entire application should wait. In an asynchronous process, the application may proceed with another job that does not depend on the Web resource until the task potentially causing the lock ends.


Reference:

Visual C#: Thread.Sleep vs. Task.Delay. Available in: https://msdn.microsoft.com/pt-br/library/hh191443(v=vs.120). aspx? f=255&mspperror=-2147217396#Anchor_0. Accessed: 08 Dec. 2017.

Asynchronous programming with Async and Await (C# and Visual Basic). Available in: https://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx. Accessed: 08 Dec. 2017.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.