Task.ContinueWith query

本文关键字:query ContinueWith Task | 更新日期: 2023-09-27 18:17:16

我是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"); }));

Task.ContinueWith query

你所做的第一个方法调用链以 ContinueWith() 结尾,它返回一个无法分配给Task<List<int>>Task对象:

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"); }));