简体   繁体   English

以异步方法返回Task.Run

[英]return Task.Run in an async method

How would you rewrite TaskOfTResult_MethodAsync to avoid the error: Since this is an async method, the return expression must be of type int rather than Task<int> . 您将如何重写TaskOfTResult_MethodAsync以避免错误:由于这是一个异步方法,因此返回表达式必须为int类型,而不是Task<int>

private static async Task<int> TaskOfTResult_MethodAsync()
{
    return Task.Run(() => ComplexCalculation());
}

private static int ComplexCalculation()
{
    double x = 2;
    for (int i = 1; i< 10000000; i++)
    {
        x += Math.Sqrt(x) / i;
    }
    return (int)x;
}

Simple; 简单; either don't make it async : 要么不使其async

private static Task<int> TaskOfTResult_MethodAsync()
{
    return Task.Run(() => ComplexCalculation());
}

or await the result: await结果:

private static async Task<int> TaskOfTResult_MethodAsync()
{
    return await Task.Run(() => ComplexCalculation());
}

(adding the await here is more expensive in terms of the generated machinery, but has more obvious/reliable exception handling, etc) (就生成的机器而言,在此处添加await更为昂贵,但具有更明显/可靠的异常处理等)

Note: you could also probably use Task.Yield : 注意:您也可以使用Task.Yield

private static async Task<int> TaskOfTResult_MethodAsync()
{
    await Task.Yield();
    return ComplexCalculation();
}

(note that what this does depends a lot on the sync-context, if one) (请注意,此操作很大程度上取决于同步上下文,如果有的话)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM