PLINQ to Entity Framework: why shouldn't it be used?

entity-framework entity-framework-6 plinq


I read somewhere that you shouldn't use PLINQ on Entity Framework or SQL. I can't remember where I read it or what the reasons were, but I did some experimentation. Using traditional LINQ to Entity Framework to load a database table that's expected to grow to be quite large currently takes 12 to 13 milliseconds. However, when I add .AsParallel() the same query runs in 2 to 4 milliseconds, and I get the same exact results.

So if I get the same results faster using PLINQ, what are the pitfalls of using PLINQ to Entity Framework?

2/15/2018 2:02:04 PM

Accepted Answer

There are some dangers, IE the the DbContext cannot be accessed by multiple threads simultaneously. And often little upside, ie PLINQ will synchronize access to IEnumerable.MoveNext() which does all the work of reading the data, creating the Entities and interacting with the change tracker.

But if you do a lot of work with the returned entities, that does not touch the DbContext (ie no SaveChanges(), no Lazy Loading, etc), you can use PLINQ.

But most of the examples I can think of would be better-optimized by building the operation into the original query, or by performing server-side raw SQL.

So if you have a bunch of CPU-intensive domain logic you need to run across a collection of entities, you could operate across the results in parallel, but you might be better-off creating a separate DbContext inside the parallel execution block.

2/15/2018 3:01:51 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow