obautista obautista - 15 days ago 5
C# Question

Using Async with WebAPI2 and Entity Framework 6 with .Net 4.6

I had set up my controller and service layer to not use async and Task originally. I updated my code (below). Is this the correct way to use async, Task, and await? Will my code benefit long term as number of users grow?

Controller:



public async Task<IHttpActionResult> All()
{
var warmup = await _warmupService.GetAllAsync();

if (warmup != null)
return Ok(warmup);

return NotFound();
}





The Controller calls this method in my service layer:



public async Task<Warmup> GetAllAsync()
{
return await Task.Run(() => GetWarmup());
}





GetWarmup() (also in Service) makes a DB call using EF6:



private Warmup GetWarmup()
{
var warmup = new Warmup();

var factoryTools = _db.FactoryTools.Select(tool => new { tool.Factory });
}




Answer

It is not the best way to do it. If you can, avoid using Task.Run when your underlying code provides a Task or Task<T> you can await.

Instead of using Task.Run in this piece of code

public async Task<Warmup> GetAllAsync()
{            
    return await Task.Run(() => GetWarmup());
}

and using this:

private Warmup GetWarmup()
{
    var warmup = new Warmup();

    var factoryTools = _db.FactoryTools.Select(tool => new { tool.Factory });
}

you should use the native async methods provided by the Entity Framework like demoed here: https://msdn.microsoft.com/en-us/library/jj819165(v=vs.113).aspx

So your GetWarmUp() should be async Task<Warmup>() and call one of the native async methods of the Entity Framework.

See https://msdn.microsoft.com/en-us/library/system.data.entity.queryableextensions(v=vs.113).aspx for a list of available async extension methods.

Comments