I have a simple ASP.NET Web API project. Now I want to make all basic methods as asynchronous. I tried to do something, and it's working but I'm not sure that it was implemented properly.
Please check whether I properly implemented async
/await
in my project.
I had implemented methods like below in my repository:
public T GetById(object id)
{
return this.Entities.Find(id);
}
public void Insert(T entity)
{
try
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
this.Entities.Add(entity);
this.context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
errorMessage += string.Format("Property: {0} Error: {1}",
validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
}
}
throw new Exception(errorMessage, dbEx);
}
}
I tried to create async
methods:
public Task InsertAsync(T entity)
{
return Task.Run(() => Insert(entity));
}
public Task<T> GetByIdAsync(object id)
{
return Task.Run(() => GetById(id));
}
And now I'm using it as:
public async virtual Task<HttpResponseMessage> Post([FromBody]T entity)
{
try
{
await repository.InsertAsync(entity);
return Request.CreateResponse(HttpStatusCode.Created, entity);
}
catch (Exception ex)
{
return ErrorMsg(HttpStatusCode.InternalServerError, ex.Message);
}
}
public async virtual Task<HttpResponseMessage> GetById(int id)
{
var entity = await repository.GetByIdAsync(id);
if (entity == null)
{
var message = string.Format("No {0} with ID = {1}", GenericTypeName, id);
return ErrorMsg(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, entity);
}