Task.WaitAll not waiting - Explanation

The following code ( LINQPadSample) should create 5 work tasks and wait for the completion of all these actions.

Instead, it launches 5 tasks and immediately displays a message "... Done".

The problem is (Action)- casting after Task.Run. If I delete this action, everything will work as expected.

What's going on here? This makes no sense to me, since, in my opinion, casting is superfluous.

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");
        }));
}
+4
source share
1 answer

, , async lambda ( ) Task, # Task.Run(), Func<Task>. , , , , DoWork(), , Task.Delay(). Task.WaitAll() Task.Delay().

+5

Source: https://habr.com/ru/post/1542029/


All Articles