c# - Async Await on MVC Controller with repository that selects and returns a collection -


i have mvc controller action lists of "features" have given "application" , displays table.

am using async correctly here?

the controller action async i.e.

public async task<iactionresult> list(string id) {   return view(await new featurerepository(_context).getallfeatures()); } 

and features repository (i'll instantiate via dependency injection later)...

public class featurerepository {   private applicationdbcontext _context;    public featurerepository(applicationdbcontext context)   {     _context = context;   }    public async task<iqueryable<applicationfeature>> getallfeatures()   {     var query = d in _context.applicationfeatures                 select d;      return query;    }  } 

or need use:

await query.tolistasync() 

then return list? trying avoid tolist of kind don't want run query until required i.e. defer execution.

it seems run fine before reproduce x times, wanted sure has been done in way not still behave synchronously.

thanks! dan.

(mvc 6, asp.net 5, entity framework 7, vs2015)

your await getallfeatures isn't awaiting nothing method isn't performing async operation, returning iqueryable.

so need call tolistasync somewhere. if want repo return queryable remove async/await there , use tolistasync in action.

by way, remember naming async methods async suffix suggested microsoft convention.

just clarifying when ef exposes async , when not (because doesn't have sense):

the point of async actions in mvc free iis threads when there operations not requiring iis processing. common , clear case db operations. that's why mvc async examples related ef, because can leave iis attend other requests meanwhile db processing queries.

that being said, , talking ef, ef methods expose async perform database operations. that's why don't have "addasync" (because add works dbcontext) , have "savechangesasync" (because executes db insert in case).

conclusion: take full advantage of async actions, should use ef async methods have available. if action doesn't consume async method, action shouldn't async.


Comments