Practically there are multiple instances when we want to do parallel DB call which will save us some time. Like if we want to get a few employees details as well as users detail and if both entities are independent of each other better to go with a parallel call to fetch the details.
With the growing ORM usage and enhanced & optimized framework of like
EFCore, in most of the application (related to C# development), we generally
prefer to use EFCore.
With EFCore if we try to use the same DB context to do parallel db call we are getting an error (... different thread using the same DbContext....).
Because dbContext call is not thread-safe
Parallel DB call on the same dbContext:
Code snipped: which will throw an error
private void DbCallWithParallelCallOnSameDbContext() { try { var employeesTask = _dbContext.Employees.ToListAsync(); var usersTask = _dbContext.Users.ToListAsync(); Task.WaitAll(employeesTask, usersTask); var employeesIdGreater = employeesTask.Result; var employeesIdSmaller = usersTask.Result; } catch (Exception ex) { // throw; } }
Error: screenshot:
Error: message :
One or more errors occurred. (A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to
avoid threading issues with DbContext, see
https://go.microsoft.com/fwlink/?linkid=2097913.)
How to resolve it:
Better to do the parallel DB call on separate dbContext
Code snipped to do parallel call on separate dbContext
private void DbCallWithParallelCallOnDifferentDbContext() { try { using (var dbEmployeeContext = new MyTestContext()) using (var dbUserContext = new MyTestContext()) { var employeesTask = dbEmployeeContext.Employees.ToListAsync(); var usersTask = dbUserContext.Users.ToListAsync(); Task.WaitAll(employeesTask, usersTask); var employeesIdGreater = employeesTask.Result; var employeesIdSmaller = usersTask.Result; } } catch (Exception ex) { //TODO: logging throw; } }
Conclusion:
DbContext call is not thread-safe. If we want to make parallel DB call make sure each call has its own dbContext. And also it's not safe for the parallel write operation. Do not execute parallel write operation.
Comments
Post a Comment