user3927354
user3927354

Reputation: 73

Task.ContinueWith query

I`m new to TPL and need some help in understanding .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"); }));

Upvotes: 0

Views: 274

Answers (1)

Alireza
Alireza

Reputation: 5056

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>>:

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.

For the first one to work, either define task as 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"); }));

Upvotes: 1

Related Questions