.Net parallel WaitAll()

Ita*_*y.B 3 .net c# parallel-processing

我的代码中有一种情况,我开始使用未知数量的任务并希望使用Task.WaitAll().

这样的事情:

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);
Run Code Online (Sandbox Code Playgroud)

问题是我不能说

Task.WaitAll(task1, task2 , task3)
Run Code Online (Sandbox Code Playgroud)

因为我不知道其中哪一个真正开始.有什么想法解决方案?

cuo*_*gle 6

您可以使用任务列表并动态地将任务添加到列表中:

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());
Run Code Online (Sandbox Code Playgroud)