Could anyone please explain this, perhaps I'm missing something obvious.
These 2 cases seem to be identical in behavior, and yet they are not.
Case 1:
Start a Task with an
async
Action,
that does some work for some time:var t = Task.Run(async () => { await Task.Delay(2000); });
A second task waits for the first one:
var waitingTask = Task.Run(() => { t.Wait(); });
Wait for the second task:
waitingTask.Wait();
Case 2:
Build a
Task
using theTask
constructor, passing the sameasync
Action
:var t = new Task(async () => { await Task.Delay(2000); });
Start another task to Wait for the first one (just like in the first case):
var waitingTask = Task.Run(() => { t.Wait(); });
Start the first task:
t.Start();
Wait for the second task:
waitingTask.Wait();
The first case behaves as expected: the waiting task ends after the first one does, after 2 seconds.
The second case is weird: the waiting task ends very quickly, long before the first one does.
It's easy to see when printing messages from both tasks. A print at the end of the second task will show the difference.
I'm using VS 2015 Preview, which probably uses Roslyn to compile, if this matters.