How does Task.Delay work exactly?

帅比萌擦擦* 提交于 2021-01-27 07:35:49

问题


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

回答1:


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.




回答2:


Modifying your DoRunAsync method as follows will make things work as intended:

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

Your code behaves as follows:

await Task.Delay(3000); // Await 3 seconds...
Console.WriteLine("One"); // Once you are done awaiting, print the string...

If you await before printing the string, you can't expect it to be printed immediately...




回答3:


The job of await is to suspend the current method until whatever awaitable you pass to it is complete. How, why and when that awaitable was created and started are of no relevance to what the await keyword accomplishes.

I think you're under the impression that await starts something, when in fact it's the opposite - it marks a point in your code where you wait for something to finish.



来源:https://stackoverflow.com/questions/47472420/how-does-task-delay-work-exactly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!