0

Consider the follow method declared with async

async Task DoOneThingOrAnother()
{
    if (condition == true)
    {
        // some non-awaitable task
        localVar = "Done";
    }
    else
    {
        // some awaitable task
        localVar = await svc.GetData();
    }
}

Although the method is declared async, are there any negative side-effects with one route through the code does not using the await?

Will a caller that uses:

await DoOneThingOrAnother();

get the same experience regardless of which path through the called method was taken?

Am curious because a warning is raised in Visual Studio if there is NO await in an async method, but not if there is a potential path through the code that does not use an await.

Neil W
  • 7,670
  • 3
  • 28
  • 41
  • 4
    You can always call non awaitable methods in an async method. Heck, you could even immediately return or throw. It's just when there's at least one await somewhere, it needs to be marked async. Has to do with state machine generation under the hood. – JHBonarius Mar 20 '21 at 20:18
  • 3
    `Will a caller get the same experience` - that depends on how technical you want to get about defining that "same". The caller will correctly proceed only after the task has completed, so it is same in that sense. However the async machinery will not be used and the entire call chain will execute synchronously if the non-await path is chosen inside `DoOneThingOrAnother`, so if you care about that, they are not the same. – GSerg Mar 20 '21 at 20:19
  • Does this answer your question? [When does 'await' immediately leave a method and when does it not?](https://stackoverflow.com/q/56723977/11683) – GSerg Mar 20 '21 at 20:25
  • The async marks the method to be split up into a statemachine. If no await is used, it can't/won't be split up. This is the reason you get a warning in visual studio. (because you might make a mistake?. – Jeroen van Langen Mar 20 '21 at 20:52

0 Answers0