Await Task.WhenAll () inside a task not expecting

My problem is that when a task has a call to Task.WhenAll () (launching other tasks), the WhenAll () line causes the consumption code to continue executing, unlike what I expect. Thus, the following code exits "complete" immediately after pressing Task.WhenAll (), and not after completing all tasks in its argument.

// Just a simple async method public Task DoWorkAsync() { return Task.Factory.StartNew( () => { // Working }); } // This one used the previous one with Task.WhenAll() public Task DoLoadsOfWorkAsync() { return Task.Factory.StartNew( async () => { // Working // This line makes the task return immediately await Task.WhenAll(DoWorkAsync(), DoWorkAsync()); // Working }); } // Consuming code await DoLoadsOfWorkAsync(); Console.WriteLine("finished"); 

I would expect WriteLine () to be called when the last line of DoLoadsOfWorkAsync () is executed.

What am I doing wrong? Thanks in advance.

+4
source share
1 answer

Task.WhenAll returns a new Task immediately, it is not blocked. The returned task will be completed when all tasks submitted to WhenAll have completed.

This is the asynchronous equivalent of Task.WaitAll , and this method is used if you want to block.

However, you have one more problem. Using Task.Factory.StartNew and passing the async delegate seems to lead to a type of Task<Task> , where the external task ends when the internal task starts to execute (and not after it completes).

Using the new Task.Run avoids this.

+18
source

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


All Articles