Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...