I got this blog once i was surfing the internet for new features in .NET 4.5. This is something interesting about PLINQ queries and its behaviours. As the title says “it’s not always guaranteed that your query is always executed parallelly”.
Yes, You may think that AsParallel() method runs in parallel for query with much faster and with increased performances. By default, PLINQ prefers to use a simple sequential algorithm over a potentially expensive parallel algorithm, and so some queries will execute sequentially, especially queries where the chain of operators do not lend themselves to parallelism. PLINQ’s intent is to run your queries as fast as possible, so if there’s a good likelihood that the complexities of parallelism will slow it down, PLINQ will perform the query sequentially rather than in parallel.
In .NET 4.5, PLINQ’s algorithms have improved over .NET 4.0 such that its set of parallelizable queries has broadened and substantially fewer queries fall back to sequential execution. In .NET 4.0, in order to force PLINQ to use a parallel algorithm, user can call;
But in .NET 4.5 the query executes is in parallel, even without the WithExecutionMode hint.
Sequential Fallback in .NET 4 and .NET 4.5
One way to illustrate the improvements to the sequential fallback is to look at the list of operators that may cause the query to fallback to sequential. Whether or not the operator actually causes a sequential fallback depends on other operators in the query as well.
Operators that may cause sequential fallback in both .NET 4 and .NET 4.5 are marked in blue, and operators that may cause fallback in .NET 4 but no longer in .NET 4.5 are marked in orange.
So, in .NET 4.5, as long as the query does not contain positional operators or the ElementAt operator, it will not fall back to sequential.
Potential Risks of the Change
The fact that some queries used to execute sequentially and now execute in parallel opens up the possibility of exposing more latent race conditions in users’ code.
There is a bug in the query above: the delegate passed into the Select operator is not thread-safe. However, the query will still happen to work in .NET 4, because as an implementation detail PLINQ decides to execute the query sequentially. In .NET 4.5, the query will run in parallel, and so list.Add(x) could be called from multiple threads concurrently, potentially resulting in a corrupted List instance.