Simon Green
Simon Green

Reputation: 1161

Do I need to always use async / await in methods already in async code flow?

Let's say I'm already in an async method, and am going to await the results of a nested method:

var x = await CallMethodAsync();

Then, let’s say you could choose to write CallMethodAsync in either of two ways:

public Task<int> CallMethodAsync() {
     var y = DoStuff();
     return _dependency.CallAnotherMethodAsync(y);
 }

or:

public async Task<int> CallMethodAsync() {
    var y = DoStuff();
    return await _dependency.CallAnotherMethodAsync(y);
}

Is there a difference? Is there any point to adding the async / await syntax in the CallMethodAsync method definition?

Upvotes: 2

Views: 59

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

The difference is subtle and is largely a trade off between:

  • getting slightly different exception semantics if an exception is thrown before the asynchronous part of CallAnotherMethodAsync
  • less overhead (allocations etc) in CallMethodAsync

Personally, I would tend not to have the await here if all of:

  • the return [await] is the very last operation
  • we do not need to transform or inspect the returned value

but it is a slightly subjective scenario. Your choice might also depend on how "hot" this code path is; if it is a high-throughput IO loop, probably avoid the await; if it is less high volume: pay the price to get the clearer exception semantics.

Upvotes: 3

Related Questions