What is the correct usage of ConcurrentBag?

前端 未结 3 1300
一生所求
一生所求 2021-02-03 17:10

I\'ve already read previous questions here about ConcurrentBag but did not find an actual sample of implementation in multi-threading.

Concur

3条回答
  •  情歌与酒
    2021-02-03 17:30

    It seems to me that bmm6o's is not correct. The ConcurrentBag instance internally contains mini-bags for each thread that adds items to it, so item insertion does not involve any thread locks, and thus all Environment.ProcessorCount threads may get into full swing without being stuck waiting and without any thread context switches. A thread sinchronization may require when iterating over the collected items, but again in the original example the iteration is done by a single thread after all insertions are done. Moreover, if the ConcurrentBag uses Interlocked techniques as the first layer of the thread synchronization, then it is possible not to involve Monitor operations at all.

    On the other hand, using a usual List instance and wrapping each its Add() method call with a lock keyword will hurt the performance a lot. First, due to the constant Monitor.Enter() and Monitor.Exit() calls that each require to step deep into the kernel mode and to work with Windows synchronization primitives. Secondly, sometimes occasionally one thread may be blocked by the second thread because the second thread has not finished its addition yet.

    As for me, the code above is a really good example of the right usage of ConcurrentBag class.

提交回复
热议问题