.Net parallel WaitAll ()
I have a situation in my code where I am running an unknown number of tasks and would like to use Task.WaitAll()
.
something like that:
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 cannot tell
Task.WaitAll(task1, task2 , task3)
because I don't know which one will really start. Any idea for a solution?
+3
source to share
4 answers
You can use a task list and dynamically add your tasks to the list:
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());
+6
source to share
See How to: Wait for one or more tasks to complete . You can wait in the Task
s array .
0
source to share