我有几个Task
个对象,例如Task<int>
,Task<string>
,Task<double>
,我想按顺序运行。也就是说,当每个任务完成时,下一个任务将自动启动。每项任务都取决于先前任务的输出。
我该怎么做? myTask.ContinueWith(...)重载都假设一个委托参数。但是任务不是代表。
答案 0 :(得分:3)
你可以这样做:
var t1 = new Task(() => Console.WriteLine("Completed t1"));
var t2 = new Task(() => Console.WriteLine("Completed t2"));
var t3 = new Task(() => Console.WriteLine("Completed t3"));
t1.ContinueWith(t => t2.RunSynchronously())
.ContinueWith(t => t3.RunSynchronously());
t1.Start();
击> <击> 撞击>
如果你不关心任务的结果,上面的例子才有效。但是,如果您(作为编辑状态)需要将每个任务的结果传递给下一个任务,那么您可以执行以下操作:
var t1 = new Task(() => Console.WriteLine("Completed t1"));
var t2 = new Task(() => Console.WriteLine("Completed t2"));
var t3 = new Task(() => Console.WriteLine("Completed t3"));
t1.ContinueWith(task1 =>
{
Console.WriteLine(task1.Result);
t2.ContinueWith(task2 =>
{
Console.WriteLine("{0} | {1}", task1.Result, task2.Result);
t3.ContinueWith(task3 =>
{
Console.WriteLine("{0} | {1} | {2}",
task1.Result, task2.Result, task3.Result);
});
t3.Start();
});
t2.Start();
});
t1.Start();
/* OUTPUT:
Completed t1
Completed t1 | Completed t2
Completed t1 | Completed t2 | Completed t3 */