Do the tasks continue asynchronous relationships with each other?

I searched, but cannot find explicit confirmation anywhere ... If a task has several continuations (not chain continuations), are these continuations performed parallel to each other?

I want to run task1 and then task2-task3-task4 in parallel to each other and finally task5 when it is all over. An example is below. Will tasks 2, 3, and 4 definitely execute asynchronously with each other?

While we are in this matter, any suggestions for improving the template are welcome. There seem to be several different ways to achieve this composition. Thanks

public Task MyWorkflowAsync() { Task task1 = Task.Factory.StartNew( () => DoTask1() ); var tarray = new Task[] { task1.ContinueWith( task => DoTask2() ), task1.ContinueWith( task => DoTask3() ), task1.ContinueWith( task => DoTask4() ) }; return Task.Factory.ContinueWhenAll( tarray, completedTasks => DoTask5() ); } 
+4
source share
1 answer

No, continuations are performed in the default scheduler LIFO ordering. If you want all of them to work in parallel, you should do this:

 public Task MyWorkflowAsync() { var tasks = new List<Task>(); var task1 = Task.Factory.StartNew(DoTask1); tasks.Add(task1.ContinueWith(task => tasks.Add(Task.Factory.StartNew(DoTask2)))); tasks.Add(task1.ContinueWith(task => tasks.Add(Task.Factory.StartNew(DoTask3)))); tasks.Add(task1.ContinueWith(task => tasks.Add(Task.Factory.StartNew(DoTask4)))); return Task.Factory.ContinueWhenAll(tasks.ToArray(), completedTasks => DoTask5()); } 
+3
source

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


All Articles