Reputation: 195
Is there a best practice for a design for a data access layer that could have both a need for Async and Non-Async calls?
I've seen some other posts that seem to be saying that using Task.Run on async calls is a "work-around" to calling async methods synchronously.
Example of a method I have (service layer) that could be leveraged both ways.
public override async Task<DataAccess.Fight> Insert(DataAccess.Fight item)
{
await UnitOfWork.Fight.Insert(item);
return item;
}
Thanks. v.
Upvotes: 1
Views: 449
Reputation: 456332
Is there a best practice for a design for a data access layer that could have both a need for Async and Non-Async calls?
First, I'd recommend only exposing asynchronous methods. Data access, being I/O-based, is inherently asynchronous, so only exposing asynchronous methods is IMO an acceptable solution.
If you really need both asynchronous and synchronous methods, I recommend using the bool argument hack, which allows you to have both synchronous and asynchronous APIs without duplicating any logic.
I've seen some other posts that seem to be saying that using Task.Run on async calls is a "work-around" to calling async methods synchronously.
I believe you are referring to the thread pool hack, also covered in my article. This would not work if your code depends on any context (e.g., HttpContext.Current
). It also can shift your code's expected environment from a single-threaded (implicitly synchronized) execution to a free-threaded environment with the possibility of parallelism. Most code is OK with this, but this does illustrate that "just wrap it in Task.Run
and then block" is not a solution for every scenario.
Upvotes: 3