Ok, I found the answer myself after reading this https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/
By using the async keyword here, the compiler is going to map this
delegate to be a Func<Task<int>>
: invoking the delegate will return
the Task<int>
to represent the eventual completion of this call. And
since the delegate is Func<Task<int>>
, TResult
is Task<int>
, and thus
the type of ‘t’ is going to be Task<Task<int>>
, not Task<int>
.
So this code works as expected:
Task[] tasks = new Task[4];
for (var i = 0; i < tasks.Length; ++i) {
tasks[i] = Task.Factory.StartNew(async () =>
{
await Task.Delay(4000);
});
}
for (var i = 0; i < tasks.Length; ++i)
await await (tasks[i] as Task<Task>);
Console.WriteLine("Done!");
Which can be implemented also using Unwrap
:
Task[] tasks = new Task[4];
for (var i = 0; i < tasks.Length; ++i) {
tasks[i] = Task.Factory.StartNew(async () =>
{
await Task.Delay(4000);
}).Unwrap();
}
for (var i = 0; i < tasks.Length; ++i)
await tasks[i];
Console.WriteLine("Done!");