難道不可以將任務添加到Task.WhenAll
已在等待的列表中嗎?如何將任務添加到Task.WhenAll正在等待的集合中?
我想等待所有任務完成,並且有可能在初始化後創建新的任務。但是這裏Task.WhenAll
不會等待稍後添加到集合中的新任務。
List<Task> tasks = new List<Task>();
var task1 = Task.Run(async() =>
{
Debug.WriteLine("task #1 started");
await Task.Delay(TimeSpan.FromSeconds(20));
Debug.WriteLine("task #1 finished");
});
var task2 = Task.Run(async() =>
{
Debug.WriteLine("task #2 started");
await Task.Delay(TimeSpan.FromSeconds(30));
Debug.WriteLine("task #2 finished");
});
var task3 = Task.Run(async() =>
{
Debug.WriteLine("task #3 started");
await Task.Delay(TimeSpan.FromSeconds(10));
var inner = Task.Run(async() =>
{
Debug.WriteLine("inner task started");
await Task.Delay(TimeSpan.FromSeconds(40));
Debug.WriteLine("inner task finished");
});
tasks.Add(inner);
Debug.WriteLine("task #3 finished");
});
tasks.Add(task1);
tasks.Add(task2);
tasks.Add(task3);
await Task.WhenAll(tasks);
Debug.WriteLine("All finished");
輸出:
task #2 started
task #3 started
task #1 started
task #3 finished
inner task started
task #1 finished
task #2 finished
All finished
inner task finished < didn't wait for this to finish
如果你看看[源代碼](https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,69351c6da968e5d1),你會看到集合/數組之前被複制過內部機制踢了進來,因此對原始集合的任何更改都不會被觀察到。 –
我認爲你能做的最好的是手動循環--' while(tasks.Count> 0){等待Task.WhenAll(任務); tasks = tasks.Where(t =>!t.IsCompleted); }'作爲草圖 –
@Damien_The_Unbeliever非常感謝。我認爲這是最好的解決方案。你不會把它寫成答案嗎? – Blendester