Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.WhenAll and task starting behaviour

I've got a fairly simple application using Task.WhenAll. The issue I am facing so far is that I don't know if I should start the subtasks myself or let WhenAll start them as appropriate.

The examples online show using tasks from framework methods, where it's not clear to me if the tasks returned have already started or not. However I've created my own tasks with an Action, so it's a detail that I have to address.

When I'm using Task.WhenAll, should I start the constituent tasks directly, or should I let Task.WhenAll handle it for fun, profit, and improved execution speed?

For further fun, the subtasks contain lots of blocking I/O.

like image 530
Puppy Avatar asked Oct 29 '15 09:10

Puppy


People also ask

What is task WhenAll?

Task. WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.

Can you tell difference between task WhenAll and task WhenAny?

WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.

Does task WhenAny start the tasks?

Task. WhenAll doesn't start tasks. The general pattern is that methods that return a Task , return a hot Task .

Does task WaitAll start the tasks?

WaitAll blocks the current thread until all other tasks have completed execution. The Task. WhenAll method is used to create a task that will complete if and only if all the other tasks have completed.


1 Answers

WhenAll won't start tasks for you. You have to start them yourself.

var unstartedTask = new Task(() => {});
await Task.WhenAll(unstartedTask); // this task won't complete until unstartedTask.Start()

However, generally, tasks created (e.g. using Task.Run, async methods, etc.) have already been started. So you generally don't have to take a separate action to start the task.

var task = Task.Run(() => {});
await Task.WhenAll(task); // no need for task.Start()
like image 67
Eren Ersönmez Avatar answered Sep 21 '22 11:09

Eren Ersönmez