c# - Using Async with WebAPI2 and Entity Framework 6 with .Net 4.6 -
i had set controller , service layer not use async , task originally. updated code (below). correct way use async, task, , await? code benefit long term 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 method in service layer:
public async task<warmup> getallasync() { return await task.run(() => getwarmup()); }
getwarmup() (also in service) makes db call using ef6:
private warmup getwarmup() { var warmup = new warmup(); var factorytools = _db.factorytools.select(tool => new { tool.factory }); }
it not best way it. if can, avoid using task.run
when underlying code provides task
or task<t>
can await.
instead of using task.run
in 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 native async methods provided entity framework demoed here: https://msdn.microsoft.com/en-us/library/jj819165(v=vs.113).aspx
so getwarmup()
should async task<warmup>()
, call 1 of native async methods of entity framework.
see https://msdn.microsoft.com/en-us/library/system.data.entity.queryableextensions(v=vs.113).aspx list of available async extension methods.
Comments
Post a Comment