繁体   English   中英

Task.Delay是如何工作的?

[英]How does Task.Delay work exactly?

他们说Task.Delay()是一个异步的Thread.Sleep()。 为了测试这个我写下面的代码。 我希望立即打印“One”,然后3秒后打印结果变量(15)。 在此之后2秒,将打印“Two”。 但它似乎并非如此。 “One”不会立即打印出来。 3秒后打印“One”。 为什么要等3秒钟打印“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");
    }
}
}

如下修改DoRunAsync方法将使事情按预期工作:

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

您的代码行为如下:

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

如果您打印字符串之前等待,则不能指望它立即打印...

打印"One"需要3秒钟,因为你很快就await Task.Delay

更改代码如下,以获得您期望的结果:

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

当您在打印"One"之前启动延迟任务而不await它时,后续的WriteLine可以在没有延迟的情况下完成。

await的工作是暂停当前方法,直到您传递给它的任何等待完成为止。 创建和启动await ,原因和时间await关键字的完成无关。

我认为你的印象就是await 开始了,事实上它恰恰相反 - 它标志着你在等待某些事情完成的代码中的一个点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM