PLINQ on ConcurrentQueue isn't multithreading

别说谁变了你拦得住时间么 提交于 2019-12-06 10:18:54

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);
    });

Foreach over a parallel collection is still a single threaded operation. .AsParallel returns a collection which defines a .ForAll method, which may (but by contract will not always) run in parallel. The code for that would be:

arrestQueue.AsParallel().ForAll(arrest=>
    {
        Geocoder geocodeThis = new Geocoder(arrest);
        writeQueue.Enqueue(geocodeThis.Geocode());
        Console.Out.WriteLine("Enqueued " + ++k);
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!