C# .NET Framework 4.0:在循环中链接任务
我想链接多个C# .NET Framework 4.0:在循环中链接任务,c#,.net,c#-4.0,parallel-processing,task,C#,.net,C# 4.0,Parallel Processing,Task,我想链接多个任务s,这样当一个任务结束时,下一个任务就开始了。我知道我可以通过继续来实现这一点。但是如果我有大量的任务,那么: t1继续t2 t2与t3继续 t3与t4继续 除了使用循环手动创建此链之外,还有什么好方法吗?您可以使用静态扩展continuewhalll 因此,您可以传递多个任务 更新 可以使用以下链接扩展名: public static class MyTaskExtensions { public static Task BuildChain(this Task t
任务
s,这样当一个任务结束时,下一个任务就开始了。我知道我可以通过继续来实现这一点。但是如果我有大量的任务,那么:
t1继续t2
t2与t3继续
t3与t4继续
除了使用循环手动创建此链之外,还有什么好方法吗?您可以使用静态扩展continuewhalll
因此,您可以传递多个任务
更新
可以使用以下链接扩展名:
public static class MyTaskExtensions
{
public static Task BuildChain(this Task task,
IEnumerable<Action<Task>> actions)
{
if (!actions.Any())
return task;
else
{
Task continueWith = task.ContinueWith(actions.First());
return continueWith.BuildChain(actions.Skip(1));
}
}
}
公共静态类MyTaskExtensions
{
公共静态任务构建链(此任务,
(可数动作)
{
如果(!actions.Any())
返回任务;
其他的
{
Task continueWith=Task.continueWith(actions.First());
返回continueWith.BuildChain(actions.Skip(1));
}
}
}
好吧,假设您有一些可枚举的操作
委托或您想做的事情,您可以轻松地使用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();
上面的代码实际上是您的循环,只是以一种更奇特的形式。它做同样的事情,它接受上一个任务(在使用虚拟“noop”task
启动后),然后以ContinueWith
的形式添加一个continuence(将continuence分配给循环下一次迭代过程中的当前任务,这是在调用LastOrDefault
时执行的).您能否发布代码,说明如何使用ContinueWith?这可能会引发更多的反馈。@Aliostad:我不认为这是答案,因为它们都取决于前一个正在完成的任务(t3取决于t2,t2取决于t1,等等)。是的,但我想你可以分批完成任务,所以每一个任务都可以分批完成。@Aliostad:这没有意义;OP定义的每个前一个任务都有一个明显的依赖关系,等待所有任务,然后继续将产生完全不同的效果。@Aliostad:我已经格式化了您的代码以提高可读性,但是我还将行if(actions.Count()==0)
更改为if(!actions.Any())
asCount()==0
(或Count()!=0)
)是一个@Aliostad:上面的代码还有一个问题。您正在传递操作。对于每个递归迭代,跳过(1)
。这会导致每次从一开始就对枚举进行求值,导致操作数等于N
的总和(即N+(N-1)+(N-2)+…+1
。对于大型N
,这可能会对性能产生很大影响(更不用说递归生成的堆栈了).我强烈建议你重新考虑这种方法。