Ily*_*gan 5 .net c# parallel-processing task c#-4.0
我想链接多个Tasks,这样当一个结束时,下一个s开始.我知道我可以这样做ContinueWith.但是,如果我有大量任务,那么:
t1继续t2
t2继续t3
t3继续t4
...
除了使用循环手动创建此链之外,还有一种很好的方法吗?
好吧,假设您有某种可能的Action委托或者您想要做的事情,您可以轻松地使用LINQ来执行以下操作:
// Create the base task. Run synchronously.
var task = new Task(() => { });
task.RunSynchronously();
// Chain them all together.
var query =
// For each action
from action in actions
// Assign the task to the continuation and
// return that.
select (task = task.ContinueWith(action));
// Get the last task to wait on.
// Note that this cannot be changed to "Last"
// because the actions enumeration could have no
// elements, meaning that Last would throw.
// That means task can be null, so a check
// would have to be performed on it before
// waiting on it (unless you are assured that
// there are items in the action enumeration).
task = query.LastOrDefault();
Run Code Online (Sandbox Code Playgroud)
上面的代码实际上是你的循环,只是一个更好的形式.它确实在把前面的任务(加满了一个虚拟的"空操作"后,同样的事情Task),然后在形式增添了延续ContinueWith(用于循环的下一次迭代中分配的延续,在这个过程中目前的任务,在LastOrDefault被叫时执行).