Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
746 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...