How can I create new Task<T>( async( ) => { return new T( ); } );? [duplicate]

北城余情 提交于 2019-12-11 04:03:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!