1

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;
}
GSerg
  • 76,472
  • 17
  • 159
  • 346
Sami
  • 113
  • 3
  • 12
  • 2
    Possible duplicate of [async await return Task](https://stackoverflow.com/questions/25191512/async-await-return-task) – GSerg Oct 24 '18 at 10:34

1 Answers1

7

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)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • In what way is the exception handling more obvious/reliable? When I test it, they are the same (other than the `await` version has more lines in the stack trace.) – pere57 Oct 24 '18 at 18:06