C# Parallel Vs. Threaded code performance

前端 未结 4 1141
耶瑟儿~
耶瑟儿~ 2021-02-14 03:19

I\'ve been testing the performance of System.Threading.Parallel vs a Threading and I\'m surprised to see Parallel taking longer to finish tasks than threading. I\'m sure it\'s d

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-14 03:57

    Refering to a blog post by Reed Copsey Jr:

    Parallel.ForEach is a bit more complicated, however. When working with a generic IEnumerable, the number of items required for processing is not known in advance, and must be discovered at runtime. In addition, since we don’t have direct access to each element, the scheduler must enumerate the collection to process it. Since IEnumerable is not thread safe, it must lock on elements as it enumerates, create temporary collections for each chunk to process, and schedule this out.

    The locking and copying could make Parallel.ForEach take longer. Also partitioning and the scheduler of ForEach could impact and give overhead. I tested your code and increased the sleep of each task, and then the results are closer, but still ForEach is slower.

    [Edit - more research]

    I added the following to the execution loops:

    if (Thread.CurrentThread.ManagedThreadId > maxThreadId)
       maxThreadId = Thread.CurrentThread.ManagedThreadId;
    

    What this shows on my machine is that it uses 10 threads less with ForEach, compared to the other one with the current settings. If you want more threads out of ForEach, you would have to fiddle around with ParallelOptions and the Scheduler.

    See Does Parallel.ForEach limits the number of active threads?

提交回复
热议问题