Wrap a synchronous method into an async one which can be 'waited' upon

試著忘記壹切 提交于 2020-01-02 01:59:17

问题


I have a synchronous call:

_context.User.Where((u) => (u.UserID == twitterId && u.Type == UserType.Show)).SingleOrDefault();

That I need to wrap into an async one which I can wait on using the await keyword.

How can I achieve this?

Thanks.


回答1:


You need to wrap your sync call using Task.Run method.

var user = await Task.Run(() => 
   _context.User
           .Where(u => u.UserID == twitterId && u.Type == UserType.Show)
           .SingleOrDefault());

Keep in mind that EntityFramework in version 6.0 will have async interfaces, so you would no longer need to use this code.




回答2:


QueryableExtensions, added in EF6, make this a breeze:

await _context.User.SingleOrDefaultAsync(u => 
    u.UserID == twitterId 
    && u.Type == UserType.Show);

Don't forget to reference System.Data.Entity in the EntityFramework.dll



来源:https://stackoverflow.com/questions/18023333/wrap-a-synchronous-method-into-an-async-one-which-can-be-waited-upon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!