Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Task or await and ConfigureAwait(false)

Tags:

c#

async-await

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

like image 915
sevenmy Avatar asked May 08 '14 08:05

sevenmy


1 Answers

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.

like image 140
noseratio Avatar answered Oct 18 '22 14:10

noseratio