簡體   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