Can a List be accessed by multiple threads?

后端 未结 4 2084

I am planning to share a List between multiple threads. The list will be locked during a changes, which happen infrequently. Is there a thread safety issue if multiple itera

4条回答
  •  盖世英雄少女心
    2021-01-02 03:12

    If you can (if you can use .NET 4 that is), use BlockingCollection:

    Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection.

    If not then encapsulate the list completely and add thread-safe methods that access the List's state. Don't make the reference to the list public or return it from any methods - always encapsulate the reference so you can guarantee that you are locking around all access to it.

提交回复
热议问题