Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Task.Delay work exactly?

They say Task.Delay() is an async Thread.Sleep(). To test this I wrote below code. I expect to print immediately "One" then 3 seconds later result variable (15) will be printed. 2 seconds after this, "Two" will be printed. But it doesnt seem so. "One" is not immediately printed. "One" is printed 3 seconds later. Why does it wait 3 seconds to print "One" ?

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication31
{
class Program
{
    public static int Multiply(int a, int b)
    {
        return a * b;
    }

    public static async Task DoRunAsync(int m, int n)
    {
        int result = await Task.Run(() => Multiply(m, n));
        await Task.Delay(3000);
        Console.WriteLine("One");
        Console.WriteLine(result);
    }

    static void Main(string[] args)
    {
        Task t = DoRunAsync(3, 5);
        Thread.Sleep(5000);
        Console.WriteLine("Two");
    }
}
}
like image 700
Lyrk Avatar asked Nov 24 '17 11:11

Lyrk


1 Answers

It takes 3 seconds to print "One" because you await-ed Task.Delay too soon.

Change the code as follows to get the result that you expected:

int result = await Task.Run(() => Multiply(m, n));
var taskDelay = Task.Delay(3000); // No blocking here, so
Console.WriteLine("One");                              // printing can proceed.
await taskDelay; // This causes a block for the remainder of 3 seconds
Console.WriteLine(result);

When you start the delay task prior to printing "One" without await-ing it, subsequent WriteLine could complete without a delay.

like image 80
Sergey Kalinichenko Avatar answered Sep 28 '22 04:09

Sergey Kalinichenko