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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…