How to create a new task <T> (async () => {return new T ();}) ;?

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

I would like this task to return a value (preferably through await ing).

I would also like to be able to await methods / functions as part of this task.

When I try to create a simple conceptual function that should do what I want, I get a message with a red line:

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

Error: Cannot convert lambda expression to type 'object' because it is not a delegate type

As soon as I remove the async from lambda, everything is hunky dory.

How can i fix this? Can i fix this?

+2
c # lambda asynchronous task
source share
2 answers

I found the answer after digging a little more. In case someone is faced with this exact problem, an answer already exists .

Abbreviation:

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

becomes

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

you need to explicitly point it to Func<Task<object>> , or if you want things to be more readable, you could confirm 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( ){ } 
0
source share