Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Data Context - Async/Await & Multithreading

I frequently use async/await to ensure ASP.NET MVC Web API threads are not blocked by longer-running I/O and network operations, specifically database calls.

The System.Data.Entity namespace provides a variety of helper extensions here, such as FirstOrDefaultAsync, ContainsAsync, CountAsync and so forth.

However, since data contexts are not thread safe, this means that the following code is problematic:

var dbContext = new DbContext(); var something = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 1); var morething = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 2); 

In fact, I'm sometimes seeing exceptions such as:

System.InvalidOperationException: The connection was not closed. The connection's current state is open.

Is the correct pattern then to use a separate using(new DbContext...) block for each asynchronous call to the database? Is it potentially more beneficial to just execute synchronous then instead?

like image 543
Alex Avatar asked Jan 06 '14 09:01

Alex


1 Answers

The DataContext class is part of LINQ to SQL. It does not understand async/await AFAIK, and should not be used with the Entity Framework async extension methods.

The DbContext class will work fine with async as long as you are using EF6 or higher; however, you can only have one operation (sync or async) per DbContext instance running at a time. If your code is actually using DbContext, then examine the call stack of your exception and check for any concurrent usage (e.g., Task.WhenAll).

If you are sure that all access is sequential, then please post a minimal repro and/or report it as a bug to Microsoft Connect.

like image 180
Stephen Cleary Avatar answered Sep 23 '22 14:09

Stephen Cleary