List concurrent removing and adding

前端 未结 5 1132
渐次进展
渐次进展 2020-12-17 16:36

I am not too sure, so i thought i\'d ask. Would removing and adding items to a System.Collections.Generic.List<> object be non-thread safe?

My sit

5条回答
  •  情书的邮戳
    2020-12-17 17:05

    Actually, sometimes List<> is thread-safe, and sometimes not, according to Microsoft:

    Public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

    but that page goes on to say:

    Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

提交回复
热议问题