I need to wait for one or more tasks to complete. The number of tasks that I need to wait on depends upon a few conditions. So my code is something like below.
Task[] tasks = new Task[2];
if (condition1 == true)
{
tasks[0] = Task.Factory.StartNew(() => MyMethod1());
}
if (condition2 == true)
{
tasks[1] = Task.Factory.StartNew(() => MyMethod2());
}
Task.WaitAll(tasks);
Let's say condition2
is false, so there is only one item in the tasks array. Will the WaitAll
only wait for tasks[0]
in this case?
Both Task.WaitAll and Task.WhenAll throw ArgumentException if any element of the tasks array is null.
To avoid the exception, you can add your tasks to a
List<Task>
instead: