The following code (LINQPad Sample) is expected to create 5 work tasks and wait until all of them are finished.
Instead, it starts 5 tasks and immediately outputs the "... Done" - message.
The problem is the (Action) - cast after Task.Run. If I remove that cast, everything works as expected.
What happens here? It doesn't make any sense to me since in my opinion the cast is redundant.
void Main() { var tasks = Enumerable.Range(1, 5).Select(x => this.DoWork()).ToArray(); Console.WriteLine("Waiting ... "); Task.WaitAll(tasks); Console.WriteLine("... Done"); } Task DoWork() { return Task.Run( (Action)(async () => { Console.WriteLine("Task start"); await Task.Delay(3000); Console.WriteLine("Task end"); })); }
asyncbefore the()in the task you create inDoWork. The task you create creates another task which it does not wait for and returns immediately.