顺序.net任务

本文关键字:任务 net 顺序 | 更新日期: 2023-09-27 18:16:33

我有几个Task对象,如Task<int>, Task<string>, Task<double>,我想按顺序运行。也就是说,当每个Task完成时,下一个Task会自动启动。每个任务都依赖于前一个任务的输出。

我该怎么做?myTask.ContinueWith(…)重载都假定有一个委托参数。但是Task不是委托

顺序.net任务

你可以这样做:

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 */