user400055
user400055

Reputation:

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

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.

Upvotes: 8

Views: 2579

Answers (2)

2Toad
2Toad

Reputation: 15038

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

Upvotes: 3

ghord
ghord

Reputation: 13797

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.

Upvotes: 11

Related Questions