简体   繁体   English

Task.ContinueWith查询

[英]Task.ContinueWith query

I`m new to TPL and need some help in understanding .continueWith. 我是TPL的新手,需要一些帮助来了解.continueWith。 Can you pls tell me what is wrong in first task-continuation and how is second one correct? 您能告诉我第一个任务继续执行中有什么问题,第二个正确吗?

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

The first chain of method calls you made ends with ContinueWith() which returns a Task object which can't be assigned to a Task<List<int>> : 您进行的第一个方法调用以ContinueWith()结尾,该方法返回一个Task对象,该对象无法分配给Task<List<int>>

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

But in the second one, the result of the last ContinueWith is not assigned to anything, so works fine. 但是在第二个中,最后一个ContinueWith的结果未分配给任何东西,因此工作正常。

For the first one to work, either define task as Task : 对于第一个有效的方法,可以将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"); }));

Or make the last call a generic one: 或将最后一个呼叫设为通用呼叫:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM