Will every 'await' operator result in a state machine?

后端 未结 3 868
北海茫月
北海茫月 2020-12-17 23:51

Please consider the following code:

public async Task GetString()
{
    //Some code here...
    var data = await A();
    //Some more code...
          


        
3条回答
  •  北海茫月
    2020-12-18 00:05

    await doesn't matter in this case. Each async method will generate a state machine (even if it has no awaits at all).

    You can see that with this TryRoslyn example.

    If you have cases where a state machine isn't needed, where the method doesn't really need to be async like this one for example:

    private async Task D()
    {
        var data = await FetchFromDB();
        return data;
    }
    

    You can remove the async keyword and the state machine that comes with it:

    private Task D()
    {
        return FetchFromDB();
    }
    

    But otherwise, you actually need the state machine and an async method can't operation without it.

    You should note that the overhead is quite small and is usually negligible compared to the resources saved by using async-await. If you realize that's not the case (by testing) you should probably just make that operation synchronous.

提交回复
热议问题