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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With