user20543568
user20543568

Reputation:

How to get a return value from a Task?

I have a task that needs to return a value, which is to be passed to the ContinueWith. However, I have no idea what the Task<<PlaceHolder>TResult> / Func<<PlaceHolder>TResult> syntax is:

This is my current code:

var task = new Task(CreateAction(token), token, TaskCreationOptions.AttachedToParent);
task.ContinueWith(_ => {/*...*/});
//...

Action CreateAction(CancellationToken cancellationToken)
{
    return async () => 
    {
       //... 
       // Need to modify this method to return a bool value
    }
}

I've tried this but it doesn't compile:

var task = new Task<bool>(CreateAction(token), token, TaskCreationOptions.AttachedToParent);
task.ContinueWith((theReturnValue) => {/*...*/});
//...

Func<bool> CreateAction(CancellationToken cancellationToken)
{
    return async () => 
    {
       //... 
       return true; // hardcoded for example sake
    }
}

Upvotes: 1

Views: 350

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

The direct answer is:

task.ContinueWith(t =>
{
    var foo = t.Result;
    // etc
});

however, ContinueWith probably isn't necessary here; this sounds like await:

var foo = await task;

Note also that new Task(...) is unusual (see "Remarks" here); I would expect more of Task.Run here.

Upvotes: 3

Related Questions