Why are there no concurrent collections in C#?

前端 未结 3 945
我寻月下人不归
我寻月下人不归 2021-02-13 03:08

I am trying to get an overview of the thread safety theory behind the collections in C#.

Why are there no concurrent collections as there are in Java? (java docs). Some

3条回答
  •  旧时难觅i
    2021-02-13 03:34

    C# offers several ways to work with collections across multiple threads. For a good write-up of these techniques I would recommend that you start with Collections and Synchronization (Thread Safety):

    By default, Collections classes are generally not thread safe. Multiple readers can read the collection with confidence; however, any modification to the collection produces undefined results for all threads that access the collection, including the reader threads.

    Collections classes can be made thread safe using any of the following methods:

    • Create a thread-safe wrapper using the Synchronized method, and access the collection exclusively through that wrapper.
    • If the class does not have a Synchronized method, derive from the class and implement a Synchronized method using the SyncRoot property.
    • Use a locking mechanism, such as the lock statement in C# (SyncLock in Visual Basic), on the SyncRoot property when accessing the collection.

提交回复
热议问题