Reputation: 4111
I have a situation in my code where i'm starting unknown number of tasks and would like to use Task.WaitAll()
.
something like this:
if (condition)
{
var task1 = Task.Factory.StartNew (call the web service1...);
}
if (condition)
{
var task2 = Task.Factory.StartNew (call the web service2...);
}
if (condition)
{
var task3 = Task.Factory.StartNew (call the web service3...);
}
Task.WaitAll(task1, task2, task3);
The problem is that i can't say
Task.WaitAll(task1, task2 , task3)
because i don't know which one of them will actually start. Any idea for a solution?
Upvotes: 3
Views: 1050
Reputation: 75306
You can use the list of Tasks and add your tasks into list dynamically:
var tasks = new List<Task>();
if (condition)
{
var task = Task.Factory.StartNew (call the web service1...);
tasks.Add(task);
}
if (condition)
{
var task2 = Task.Factory.StartNew (call the web service2...);
tasks.Add(task2);
}
if (condition) {
var task3 = Task.Factory.StartNew (call the web service3...);
tasks.Add(task3);
}
Task.WaitAll(tasks.ToArray());
Upvotes: 6
Reputation: 12215
Create a list of actually started tasks and do Task.WaitAll(taskList.ToArray())
if(condition)
{
var task1 = Task.Factory.StartNew (call the web service1...);
taskList.Add(task1);
}
// etc...
Upvotes: 3
Reputation: 7737
See How to: Wait on One or More Tasks to Complete. You can wait on an array of Task
s.
Upvotes: 0
Reputation: 5340
Generally, it is possible to save the list of tasks to the List (tasks) and use the following code:
Task.WaitAll(tasks.ToArray());
Upvotes: 0