简体   繁体   中英

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> .

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 :

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

or await the result:

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)

Note: you could also probably use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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