How can I create new Task( async( ) => { return

2019-07-14 06:21发布

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?

2条回答
何必那么认真
2楼-- · 2019-07-14 06:48

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( ){
}
查看更多
甜甜的少女心
3楼-- · 2019-07-14 07:07

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 new Task<object>( (Func<Task<object>>)( async ( ) => {
        await asyncBar( );
        return new object( );
    }
}
查看更多
登录 后发表回答