13
votes

Suppose to have a service library with a method like this

public async Task<Person> GetPersonAsync(Guid id) {
  return await GetFromDbAsync<Person>(id);
}

Following the best practices for the SynchronizationContext is better to use

public async Task<Person> GetPersonAsync(Guid id) {
  return await GetFromDbAsync<Person>(id).ConfigureAwait(false);
}

But when you have only one operation (I think) is better to return the Task directly. See At the end of an async method, should I return or await?

public Task<Person> GetPersonAsync(Guid id) {
  return GetFromDbAsync<Person>(id);
}

In this last case you can't use ConfigureAwait(false) because the method is not awaited.

What is the best solution (and why)?

1
I think the last one (delegation) is the clearest and does not involve creation of additional state machine. Unless you're doing something else inside the method that's dependent on async call result, I see no point in using await.Patryk Ćwiek
The last one makes the most sense to me. It returns a Task which you can await from wherever you're calling GetPersonAsyncDennis_E
So the solution that return the Task directly doesn't capture the SynchronizationContext?sevenmy
What you're doing is allowing your caller to decide how they want to wait for that Task to complete - if that code is async, it can decide whether to capture context when awaiting the result.Damien_The_Unbeliever
@Damien_The_Unbeliever ok, thus in the latest example there's not the switching context overhead?sevenmy

1 Answers

10
votes

Each option has its own specifics, check this and this. If you understand them, you could decide what's the best one for you.

So the solution that return the Task directly doesn't capture the SynchronizationContext?

It's not the task that captures the current synchronization context. It's TaskAwaiter.OnCompleted (or ConfiguredTaskAwaitable.OnCompleted, in case of ConfigureAwait), which is indirectly invoked by the code generated by C# compiler as a part of the await statement for the task.

So, if you don't use await, you shouldn't be worried about SynchronizationContext capturing, it doesn't magically happen on its own. This probably makes the 3rd option the most favorable one, but keep in mind its exception propagation behavior.