Álvaro García
Álvaro García

Reputation: 19396

How to wait all task when I not always I run some of them?

I wanted to run some code in parallel using tasks, but some of this parallel code sometimes I have to run and sometimes not. Depends of some conditions. So I was thinking in a code like that:

Task myTsk01 = null;
Task myTsk02 = null;
Task myTsk03 = null;

if(condition01 true) myTask01 = Task.Run(() => myCode01);
if(condition02 true) myTask02 = Task.Run(() => myCode02);
if(condition03 true) myTask03 = Task.Run(() => myCode03);

Task.WaitAll(myTsk01, myTsk02, myTsk03);

However, with this code, I get an error because sometimes at least one task is null.

So I Have tried another option:

Task myTsk01 = null;
 Task myTsk02 = null;
 Task myTsk03 = null;
 List<Task> myLstTasks = new List<Tasks>();
 if(condition01 true) miLstTasks.Add(Task.Run(() => myCode01));
 if(condition02 true) miLstTasks.Add(Task.Run(() => myCode02));
 if(condition03 true) miLstTasks.Add(Task.Run(() => myCode03));

 Task.WaitAll(myLstTasks.ToArray());

In this case I can get the same error if the list is empty because all conditions are false.

So my last solution is:

 Task myTsk01 = null;
 Task myTsk02 = null;
 Task myTsk03 = null;
 List<Task> myLstTasks = new List<Tasks>();
 if(condition01 true) miLstTasks.Add(Task.Run(() => myCode01));
 if(condition02 true) miLstTasks.Add(Task.Run(() => myCode02));
 if(condition03 true) miLstTasks.Add(Task.Run(() => myCode03));

 if(myListTsk.Count > 0) Task.WaitAll(myLstTasks.ToArray());

This solution works, but I think that to use an if to check if the list is empty is not the best way to do it, because I guess that run tasks according to a condition and wait all of them it has to be a common case. But I don't be able to find a better solution.

So I would like to know if this is the best solution or if there are any other that is better.

Thanks.

Upvotes: 1

Views: 255

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32063

This would work just fine, without having to reference the Tasks individually:

List<Task> tasks = new List<Tasks>();

if(condition01) 
    tasks.Add(Task.Run(() => myCode01));
if(condition02)
    tasks.Add(Task.Run(() => myCode02));
if(condition03) 
    tasks.Add(Task.Run(() => myCode03));

Task.WaitAll(tasks.ToArray());

There's also no need to check whether tasks is empty.

Upvotes: 4

Related Questions