Suppose to have a service library with a method like this
public async Task GetPersonAsync(Guid id) {
return await GetFromDbAsync
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.