3

I need to create a function which will return a task that will be executed at another time.

I would like for that task to return a value (preferably through awaiting it).

I would also like to be able to await methods/functions within that task.

When I try to create a simple conceptual function which should do what I want, I get a red-line error message :

private static Task<object> FooGet( ) {
    return new Task<object>( async ( ) => {
        await asyncBar( );
        return new object( );
    } );
}

The error reads : Cannot convert lambda expression to type 'object' because it is not a delegate type

As soon as I remove the async keyword from the lambda, everything's hunky dory.

How can I fix this? Can I even fix this?

Will
  • 3,413
  • 7
  • 50
  • 107

2 Answers2

2

I found the answer after digging a bit more. In case someone runs into this precise issue the answer already exists.

Shorthand :

private static Task<object> FooGet()
{
    return new Task<object>(async () =>
    {
        await asyncBar();
        return new object();
    });
}

becomes

private static Task<object> FooGet()
{
    return ((Func<Task<object>>)(async () =>
    {
        await asyncBar();
        return new object();
    }))();
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Will
  • 3,413
  • 7
  • 50
  • 107
  • Since you have added to another answer, I think it is perfectly OK to get upvotes. However if you are determined not to receive them, you can always add an answer as community wiki, which mostly removes your ownership from the post. – halfer Feb 15 '16 at 19:50
  • @halfer I... have literally no idea what you are talking about. Can I have some context, please? – Will Feb 15 '16 at 22:43
  • See the edit I made to your answer - you asked people to upvote another answer and explicitly not your own. I edited that out since I felt it was excessive meta-commentary, but in any case I thought you were being rather unfair to yourself, and that your own question merited upvotes if people wish to give them. – halfer Feb 15 '16 at 22:54
  • @halfer The world literally. – Will Feb 15 '16 at 23:44
0

you need to explicitly cast it to Func<Task<object>> or if you want to keep things more readable you could refactory this as

private static Task<object> FooGet( ) {
    return new Task<object>(innerTask);
}

private async static Task<object> innerTask() {
    await asyncBar( );
    return new object( );
}

private static async Task asyncBar( ){
}
Not Important
  • 762
  • 6
  • 22