Why does iterating over GetConsumingEnumerable() not fully empty the underlying blocking collection

前端 未结 4 2027
天涯浪人
天涯浪人 2021-02-04 04:16

I have a quantifiable & repeatable problem using the Task Parallel Library, BlockingCollection, ConcurrentQueue & GetCo

4条回答
  •  我寻月下人不归
    2021-02-04 05:01

    You can't use GetConsumingEnumerable() in Parallel.ForEach().

    Use the GetConsumingPartitioner from the TPL extras

    In the blog post you will also get an explanation why can't use GetConsumingEnumerable()

    The partitioning algorithm employed by default by both Parallel.ForEach and PLINQ use chunking in order to minimize synchronization costs: rather than taking the lock once per element, it'll take the lock, grab a group of elements (a chunk), and then release the lock.

    i.e. Parallel.ForEach wait until it receives a group of work items before continuing. Exactly what your experiment shows.

提交回复
热议问题