3

why does the method AwakeTest take 3 seconds instead of one

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;
}
Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
fubo
  • 44,811
  • 17
  • 103
  • 137
  • Check this out http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr – Mihail Shishkov Apr 15 '15 at 09:58

1 Answers1

11

Since Thread.Sleep sleeps the thread, and each Task doesn't require to run in a separate thread, it hangs the entire thread.

You should use Task.Delay instead:

await Task.Delay(Seconds * 1000);
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 1
    d'oh i expected `Do1`, `Do2`, `Do3` to be handled in seperate threads - thanks! – fubo Apr 15 '15 at 10:01
  • I think the linked question is irrelevant here. It is about `TasFactory.StartNew` or its related methods. Not just asynchronous methods. – Sriram Sakthivel May 07 '15 at 07:00
  • @SriramSakthivel: Okay, but he is running them as tasks, right? He calls `System.Threading.Tasks.Task.WhenAll`. – Patrick Hofman May 07 '15 at 07:09
  • That doesn't makes it relevant too. For example you could write `await Task.WhenAll(Task.FromResult(1), Task.FromResult(2), ...); `. Here OP already know there is no thread involved. Mere use of tasks doesn't makes it linked with Thread. IMHO, linked answer is irrelevant for this question. – Sriram Sakthivel May 07 '15 at 07:13