同时运行任务.NET 4.5

fub*_*ubo 3 c# task task-parallel-library async-await

为什么该方法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;
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 11

由于Thread.Sleep睡眠线程,并且每个线程Task都不需要在单独的线程中运行,因此它会挂起整个线程.

您应该使用Task.Delay:

await Task.Delay(Seconds * 1000);
Run Code Online (Sandbox Code Playgroud)