✅ EF Core long running query causing concurrency issues
Hello. I have a .NET application that uses a DbContext with PostgreSQL. To test the performance of my app, I added a million rows to one of the tables.
I noticed that it takes a pretty long time to fetch all of these rows, and if I run the method to get all the rows again before the previous query finishes, it throws the following exception:
System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext.
This is an example of how it is set up currently:
6 Replies
As the error says, multiple operations cannot be preformed on the same context at the same time. You need separate instances to be able to have multiple queries running at the same time
Right, but creating a new instance of the DbContext for every method call would be tough though wouldn't it?
no, you can just inject
IDbContextFactory<MyDbContext>
and use that
assuming you're using MSDIOh that's a thing? Wow, how did I not know that
Awesome, thanks!
dbcontexts are supposed to be short lived, i almost always new up a fresh one for each operation or tightly related set of operations
Sounds about right, I was about to write my own version of a DbContextFactory, guess I'm glad I asked here first