Where to use async/await on WebAPI
-
We've never used async/await (or something like this) in our little project. But the project is growing, and we decided to add asynchronicity.
The project has the following architecture:
- Domain (repository, EF)
- UnitTests
- Service.
- WebUI
My question is, what layer do we have to do with asynchronicity? Or do we have to do this on several layers? Please tell me where implementation will be most appropriate.
Like I have a method in the counteraller.
public virtual HttpResponseMessage Get() { var entity = Repository.GetAll();
if (entity != null && entity.Any()) { return Request.CreateResponse(HttpStatusCode.OK, entity); } var message = $"{GenericTypeName}: No content"; return ErrorMsg(HttpStatusCode.NoContent, message);
}
How do I make him asynchronous?
-
Asynchronity extends to all layers. From the bottom to the top. In your case, if Domain is asynchronous and WebUI is asynchronous. Don't forget that asynchronicity is only necessary for offshore operations (disk, network...) to ensure that, while waiting for the answer, the working flow is not cold.
class Repository { public Task<entity> GetAllAsync(CancellationToken cancellationToken) { using (var db = new DataContext()) { return db.EntitySet.ToListAsync(); } } }
public virtual async Task<IHttpActionResult> Get(CancellationToken cancellationToken)
{
var entity = await Repository.GetAllAsync(cancellationToken);if (!entity.Any()) { var message = $"{GenericTypeName}: No content"; return Content(HttpStatusCode.NoContent, message); } return Ok(entity);
}
Look at the status code 204 - No content.
For reference: https://ru.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BA%D0%BE%D0%B4%D0%BE%D0%B2_%D1%81%D0%BE%D1%81%D1%82%D0%BE%D1%8F%D0%BD%D0%B8%D1%8F_HTTP
In fact, you need to read the Task and async await. Task.Run is used for cpu bound operations (Incremental Processor operations) async awaits the result of these operations in the coded or anticipated I/O bound operations.
With regard to the entity framework, in the 6 versions, there are asynchronous methods of their name end on Async, e.g. ToListAsync().