Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# async without await

In documentation here: http://msdn.microsoft.com/en-us/library/hh191443.aspx it indicates that:

If an async method doesn’t use an await operator to mark a suspension point, the method executes as a synchronous method does, despite the async modifier. The compiler issues a warning for such methods.

I believe this is the warning:

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Then, in a different, referenced link, http://msdn.microsoft.com/en-us/library/windows/apps/hh994635.aspx, the example it shows is as follows:

public class Example
{
    // ...
    private async void NextMove_Click(object sender, RoutedEventArgs e)
    {
        await Task.Run(() => ComputeNextMove());
        // Update the UI with results
    }

    private async Task ComputeNextMove()
    {
        // ...
    }
    // ...
}

Here, I'll assume that ComputeNextMove is basically a synchronous method, itself, not calling await. That then would seem to contradict the issuance of a compiler warning (unless it's a bad example...)

If I'm not calling a .net Async method at the END of my asynchronous call stack, like HttpClient.GetStringAsync and I do want to implement some concrete "long running" synchronous logic, is there a more proper way to do it?

Perhaps my assumption is incorrect, and ComputeNextMove could be declared as private void ComputeNextMove() which would yield no warnings.

like image 586
Novox Avatar asked Dec 12 '22 07:12

Novox


1 Answers

Yes, it's just a bad example.

If ComputeNextMove is truly just a synchronous method which doesn't really do anything asynchronously (as the description suggests), it shouldn't be declared as async. It should instead be private void ComputeNextMove().

ComputeNextMove will still execute on a background thread due to the use of Task.Run.

I would quite possibly use a method group conversion instead of a lambda expression here:

await Task.Run((Action) ComputeNextMove);
like image 181
Jon Skeet Avatar answered Dec 30 '22 15:12

Jon Skeet