Difference between Thread.Sleep and Task.Delay

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

Previously, I had done another communication where I used Thread, it works without problems and consumes little processing.

At this time with Task I had a high processing, and it seemed not to happen the Delay between iterations of while. I decided to exchange all Task.Delay for Thread.Sleep.

And the result was satisfactory. He went on to have the delay with each iteration and CPU consumption remained low.

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

Code snippet where a TcpListener accepts connections (This excerpt 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
    }
}
Author: Rovann Linhalis, 2017-12-07

1 answers

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 the way above, there's nothing you can do to abort this, except wait until time runs out or restart the app. This is because Thread.Sleep suspends the segment that is making the call. And because I'm calling Thread.Sleep in my Button event handler, the UI freezes until the specified time ends.

public static Task Delay(int millisecondsDelay)

Task.Delay acts in a very different way from the 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 to respond.

Behind from the scenes there is a timer 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 the Task.Delay you have to pass over the 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 highlight is the implementation of async in the Task.Delay. Which as per documentation 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 must wait. In an asynchronous process, the application will be able to proceed with other work that does not depend on the Web resource until the potentially blocking task finishes.


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. Access on: 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. Access: 08 Dec. 2017.

 5
Author: Pablo Tondolo de Vargas, 2017-12-08 12:05:42