问题
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?
回答1:
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( ){
}
回答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();
}))();
}
来源:https://stackoverflow.com/questions/34145260/how-can-i-create-new-taskt-async-return-new-t