Parallel tasks with EF Core

Parallel Tasks with EF Core


Problem: Legacy code runs X tasks in Parallel by using ConfigureAwait(false) and/or Task.Run(() => Parallel.ForEach() which results in errors.

Background: 

    ConfigureAwait(true) OR just the regular await commands since ConfigureAwait(true) is the default means that it runs not necessarily on the same thread, but the same synchronization context. 

    ConfigureAwait(false) tells it that it does not need the context, so the code can be run anywhere. It could be any thread that runs it.  The problem is that this lack of shared context leads to errors.


Error: Because of the nature of parallelism, this error appears inconsistently: 

    "An attempt was made to use the context instance while it is being configured. A DbContext instance cannot be used inside 'OnConfiguring' since it is still being configured at this point. This can happen if a second operation is started on this context instance before a previous operation completed. Any instance members are not guaranteed to be thread safe."


Reasons: 

     1) Microsoft says Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.  Source .  One source says it is MS SQL Server specific:  "The limitation is in the Microsoft.EntityFrameworkCore.SqlServer.dll driver, and is not a generalized EF issue. The corresponding Oracle.EntityFrameworkCore.dll driver doesn't have this limitation."  Source: https://stackoverflow.com/questions/41749896/ef-6-how-to-correctly-perform-parallel-queries answer 8

     2) With ASP.NET, there is a synchronization context in .NET Framework, but none in ASP.NET Core.

     3) Not all .NET routines are thread-safe.


Workarounds:  

    1) Make your repo. methods. asynchronous (EF Core has built-in async. methods), and let the framework manages the resources, rather than using Task.Run to execute IO tasks.  

    2) Also, the rule of thumb, Task.Run for CPU-bound task, whereas async/await for I/O-bound task.


So how handle parallelism with EF Core 6+?

https://stackoverflow.com/questions/76144656/ef-core-6-parallelisation-in-dbcontext

https://stackoverflow.com/questions/41749896/ef-6-how-to-correctly-perform-parallel-queries

https://stackoverflow.com/questions/73640204/parallel-query-execution-in-entity-framework-core

https://stackoverflow.com/questions/74175945/how-to-update-a-elements-list-in-parallel-loop-with-entity-framework-core-6-0


Comments

Popular posts from this blog

Upgrading to .NET8 from desktop versions 4.8.X

JSON Web Tokens

GHL > Set website so shorter URL address