1

I have several Task objects, such as Task<int>, Task<string>, Task<double>, that I want to run sequentially. That is, as each Task completes the next Task starts automatically. Each task depends on the output from the prior task.

How do I do this? The myTask.ContinueWith(...) overloads all assume a delegate parameter. But a Task is not a delegate.

4

1 回答 1

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 */
于 2013-06-01T16:57:30.953 回答