Task.ContinueWith查询

时间:2014-08-10 16:33:24

标签: c# task-parallel-library

我是TPL的新手,需要一些帮助来理解.continueWith。你能告诉我第一次任务延续有什么问题吗?第二项任务是否正确?

List<int> input = new List<int> { 1, 2, 3, 4, 5 };

 //Gives cast error at the second continuation: cannot implicitly convert 
 //Task to Task<List<int>>
    Task<List<int>> task = Task.Factory.StartNew<List<int>>(
        (state) => { return (List<int>)state; }, input)

        .ContinueWith<List<int>>(
        (prevTask => { return (List<int>)prevTask.Result; }))

        .ContinueWith(
        (prevTask => { Console.WriteLine("All completed"); }));

    //Works fine
    Task<List<int>> task1 = Task.Factory.StartNew<List<int>>(
        (state) => { return (List<int>)state; }, input);

    task1.ContinueWith<List<int>>(
        (prevTask => { return (List<int>)prevTask.Result; }))

        .ContinueWith(
        (prevTask => { Console.WriteLine("All completed"); }));

1 个答案:

答案 0 :(得分:1)

第一个方法链调用您使用ContinueWith()结束,该对象返回Task对象,该对象无法分配给Task<List<int>>

Task.Factory.StartNew<List<int>>(...) // returns Task<List<int>>
    .ContinueWith<List<int>>(...) // returns Task<List<int>>
    .ContinueWith(...); // returns Task

但是在第二个中,最后一个ContinueWith的结果没有分配给任何东西,所以工作正常。

要使第一个工作,请将task定义为Task

Task task = Task.Factory.StartNew<List<int>>(
    (state) => { return (List<int>)state; }, input)

    .ContinueWith<List<int>>(
    (prevTask => { return (List<int>)prevTask.Result; }))

    .ContinueWith(
    (prevTask => { Console.WriteLine("All completed"); }));

或者将最后一个电话称为通用电话:

Task<List<int>> task = Task.Factory.StartNew<List<int>>(
    (state) => { return (List<int>)state; }, input)

    .ContinueWith<List<int>>(
    (prevTask => { return (List<int>)prevTask.Result; }))

    .ContinueWith<List<int>>(
    (prevTask => { Console.WriteLine("All completed"); }));