Task.WaitAll is not waiting - Explanation
.net, asynchronous, c#
Solution
I believe, it's because the async lambda (without the cast) returns Task, C# compiler chooses overload of Task.Run() method that accepts `Func<Task>` delegate. If you cast the delegate to Action, compiler chooses overload that accepts Action and the task returned by DoWork() method ends, when `Task.Delay()` method is called. The result is that `Task.WaitAll()` method ends before the `Task.Delay()` task is finished.
Problem
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"); })); } ```