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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With