I have many Tasks, that are running asynchronously
Task<bool> task1 = Task.Run<bool>(() =>
{
return this.addGroupStringToDictionary("IfcPolyline");
});
Task<bool> task2 = Task.Run<bool>(() =>
{
return this.addGroupStringToDictionary("IfcPolyLoop");
});
Task<bool> task3 = Task.Run<bool>(() =>
{
return this.addGroupStringToDictionary("IfcAxis2Placement2D");
});
Task<bool> task4 = Task.Run<bool>(() =>
{
return this.addGroupStringToDictionary("IfcAxis2Placement3D");
});
Now, I would like to execute other tasks, as soon as some of them finish.
Let's say I have 3 tasks that need to be executed after that :
task5 needs to be executed when Task1 and Task2 finished.
task6 needs to be executed when Task3 and Task4 finished.
task7 needs to be executed when Task1 and Task6 finished.
How can I do that, cause if I use await Task.WhenAll(task1,task2)
before calling task5, I also block execution of task6 and task7 ?
CodePudding user response:
You could use to your advantage the fact that the Task.Run
method accepts both synchronous and asynchronous delegates. Using an asynchronous delegate allows you to await
previously started tasks:
var task1 = Task.Run(() => { /*...*/ });
var task2 = Task.Run(() => { /*...*/ });
var task3 = Task.Run(() => { /*...*/ });
var task4 = Task.Run(() => { /*...*/ });
var task5 = Task.Run(async () =>
{
await Task.WhenAll(task1, task2);
/*...*/
});
var task6 = Task.Run(async () =>
{
await Task.WhenAll(task3, task4);
/*...*/
});
var task7 = Task.Run(async () =>
{
await Task.WhenAll(task1, task6);
/*...*/
});
CodePudding user response:
For a simple case, you can use Task.ContinueWith(). See Chaining tasks using continuation tasks on Microsoft Learn
For more complex case if you have lots of data to process, you can use DataFlow library to create a pipeline for asynchronous jobs. See How to: Implement a producer-consumer dataflow pattern