等待一个或多个任务达到特定的里程碑,异步/等待方式 [英] Wait for a task (or tasks) to reach certain milestone, the async/await way
问题描述
关于如何等待线程退出的例子很多,但有时我需要等到几个线程就绪"或达到某个里程碑.
There are tons of examples of how to wait for a thread to exit, but sometimes i need to wait just until several threads are "ready" or have reached certain milestone.
和 http://www.albahari.com/threading/
如果我已正确理解:
等待一个子任务准备就绪 :
Wait for one Child Task to be ready:
//Main Method
var wh = new AutoResetEvent(false);
Task childTask = Task.Run(() => ChildTask(wh);
wh.WaitOne();
//Child
private void ChildTask(Barrier barrier){
//do what is needed to be done before main thread continues...
wh.Set();
}
等待几个孩子准备好准备好:
//Main Method
var barrier = new Barrier(N+1);
Task childTask = Task.Run(() => ChildTask1(barrier);
Task childTask = Task.Run(() => ChildTask2(barrier);
...
Task childTask = Task.Run(() => ChildTaskN(barrier);
barrier.SignalAndWait(); //When all childs signal "ready" i will continue
OnMyEvent(); //for example, trigger an event
//Every Child
private void Child_i(Barrier barrier){
mainTask.MyEvent += MyEventHandler; //complete subscription before going any further
//do what is needed to be done before main thread continues...
barrier.SignalAndWait();
}
(请随时添加或提出其他好的模式)
(Please feel free to add or suggest another good patterns)
所以我的问题是:可以使用async/await模式来实现相同的目的吗?
So my question is: Is posible to use the async/await pattern to achieve the same?
使用这种新模式是否有优点/缺点?
Are there any advantages/disadvantages by using this new pattern?
推荐答案
您可以使用 await Task.WhenAll
或 Task.WaitAll
等待任务完成.如果要等待任务达到某个里程碑,可以将其拆分为2个任务,并使用 ContinueWith
,例如:
You can use await Task.WhenAll
or Task.WaitAll
to wait for your tasks to finish.
If you want to wait for a task to reach a certain milestone, you can split it into 2 tasks and use ContinueWith
, for example:
var task1 = Task.Run(() => Task1Part1());
task1.ContinueWith(t => Task1Part2(t.Result));
var task2 = Task.Run(() => Task2Part1());
task2.ContinueWith(t => Task2Part2(t.Result));
await Task.WhenAll(task1, task2);
这篇关于等待一个或多个任务达到特定的里程碑,异步/等待方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!