Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Entity Framework 6 function normally within Task.Run() statements?

My question is simple, if I perform a read or write within a Task.Run in order to make my method asynchronous, will it work as a normal bit of code would, or is there something within EF that bans this practice?

For example:

await Task.Run(() =>
{
    var data = _context.KittenLog.ToList();
}

I have an uneasy feeling that doing this will open a can of worms, but I can't find anything on google about combining the two.

like image 427
NibblyPig Avatar asked Feb 17 '17 15:02

NibblyPig


People also ask

Why does where () not have an asynchronous counterpart?

Note that there are no async versions of some LINQ operators such as Where or OrderBy, because these only build up the LINQ expression tree and don't cause the query to be executed in the database. Only operators which cause query execution have async counterparts.

Is Task run blocking?

Run is misused to run IO blocking tasks. Although the code will work just fine (e.g UI not not freeze) but it is still a wrong approach. This is because Task. Run will still block a thread from thread pool the entire time until it finishes the method.

Can I use Entity Framework 6 in .NET core?

To use Entity Framework 6, your project has to compile against . NET Framework, as Entity Framework 6 doesn't support . NET Core. If you need cross-platform features you will need to upgrade to Entity Framework Core.

Does Task run create a new thread?

NET code does not mean there are separate new threads involved. Generally when using Task. Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR.


1 Answers

Well yes, you could. But there is no need to wrap it in a call to Task.Run since it has native async support, see https://msdn.microsoft.com/en-us/library/jj819165(v=vs.113).aspx#Making it asynchronous

In you case it will become something like:

var data = await _context.KittenLog.ToListAsync(CancellationToken.None);

There a some things to consider. Like the context can only handle one async operation at a time.

like image 60
Peter Bons Avatar answered Sep 23 '22 23:09

Peter Bons