简体   繁体   English

同时运行任务 .NET 4.5

[英]Running Tasks simultaneously .NET 4.5

why does the method AwakeTest take 3 seconds instead of one为什么方法AwakeTest需要 3 秒而不是 1 秒

public static async void AwakeTest()
{
    var Do1 = Sleep(1, 1);
    var Do2 = Sleep(1, 2);
    var Do3 = Sleep(1, 3);

    await System.Threading.Tasks.Task.WhenAll(Do1, Do2, Do3); 

    Console.WriteLine(await Do1);
    Console.WriteLine(await Do2);
    Console.WriteLine(await Do3);
}

private static async System.Threading.Tasks.Task<int> Sleep(int Seconds, int ID)
{
    if (Seconds < 0)
    {
        throw new Exception();
    }
    System.Threading.Thread.Sleep(Seconds * 1000);
    return ID;
}

Since Thread.Sleep sleeps the thread, and each Task doesn't require to run in a separate thread, it hangs the entire thread.由于Thread.Sleep使线程休眠,并且每个Task不需要在单独的线程中运行,因此它会挂起整个线程。

You should use Task.Delay instead:您应该改用Task.Delay

await Task.Delay(Seconds * 1000);

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

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