What is the correct usage of ConcurrentBag?

前端 未结 3 1301
一生所求
一生所求 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:29

    This looks like an ok use of ConcurrentBag. The thread local variables are members of the bag, and will become eligible for garbage collection at the same time the bag is (clearing the contents won't release them). You are right that a simple List with a lock would suffice for your case. If the work you are doing in the loop is at all significant, the type of thread synchronization won't matter much to the overall performance. In that case, you might be more comfortable using what you are familiar with.

    Another option would be to use ParallelEnumerable.Select, which matches what you are trying to do more closely. Again, any performance difference you are going to see is likely going to be negligible and there's nothing wrong with sticking with what you know.

    As always, if the performance of this is critical there's no substitute for trying it and measuring.

提交回复
热议问题