如何创建新的任务< T>(异步()=> {返回新T();});? [英] How can I create new Task<T>( async( ) => { return new T( ); } );?

查看:116
本文介绍了如何创建新的任务< T>(异步()=> {返回新T();});?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建将返回,将在其他时间执行任务的功能。

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

我想那个任务返回一个值(通过 pferably $ P $等待 ING它)。

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( );
    } );
}

错误读取:无法转换拉姆达前pression键入对象,因为它不是一个委托类型

当我从拉姆达删除异步关键字,一切都虎背熊腰,脚蹬dory没问题。

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?

推荐答案

我找到了答案挖多一点了。万一有人运行到这个precise问题<一href=\"http://stackoverflow.com/questions/26946854/cannot-convert-lambda-ex$p$pssion-to-type-because-it-is-not-a-delegate-type\">the答案已经存在。

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

简写:

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

变为

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

这篇关于如何创建新的任务&LT; T&GT;(异步()=&GT; {返回新T();});?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆