I have the following PLINQ statement in a C# program:
foreach (ArrestRecord arrest in
from row in arrestQueue.AsParallel()
select row)
{
Geocoder geocodeThis = new Geocoder(arrest);
writeQueue.Enqueue(geocodeThis.Geocode());
Console.Out.WriteLine("Enqueued " + ++k);
}
Both arrestQueue
and writeQueue
are ConcurrentQueues.
Nothing is running in parallel:
geocodeThis.Geocode()
, Visual Studio's Thread dropdown just says [pid] Main Thread. It never goes to any other thread.geocodeThis.Geocode()
. Even if I add Pooling=false to the DB connection string, to force connections not to be pooled, I never see more than 1 connection used in geocodeThis.Geocode()
.This seems like a simple PLINQ case study, and I am scratching my head as to why nothing's running in parallel.
You are parallelizing just the enumeration of the assertQueue
itself and then "unparallelizing" it back into an ordinary IEnumerable
. This all happens before the foreach
loop even starts. Then you use the ordinary IEnumerable
with the foreach
which runs the body of the loop serially.
There are many ways to run the body of the loop in parallel but the first one that comes to mind is using Parallel.ForEach
:
Parallel.ForEach(arrestQueue, arrest =>
{
Geocoder geocodeThis = new Geocoder(arrest);
writeQueue.Enqueue(geocodeThis.Geocode());
Console.Out.WriteLine("Enqueued " + ++k);
});