© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
8 replies
Spaxter

✅ 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.
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:
private MyDbContext _dbContext;

public DbService(MyDbContext dbContext)
{
  _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}

// This method throws the excpetion if called again before the previous query is finished
public async Task<List<MyObj>> GetAllObjects()
{
  return await _dbContext.MyTable.AsNoTracking().ToListAsync();
}
private MyDbContext _dbContext;

public DbService(MyDbContext dbContext)
{
  _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}

// This method throws the excpetion if called again before the previous query is finished
public async Task<List<MyObj>> GetAllObjects()
{
  return await _dbContext.MyTable.AsNoTracking().ToListAsync();
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Ef-core query efficiency?
C#CC# / help
15mo ago
Migration issues -EF core.
C#CC# / help
16mo ago
EF Concurrency
C#CC# / help
12mo ago
✅ Ef Core unexpected query behaviour
C#CC# / help
17mo ago