Thread safe collections in .NET

前端 未结 4 1214
生来不讨喜
生来不讨喜 2020-11-29 22:16

What is the standard nowadays when one needs a thread safe collection (e.g. Set). Do I synchronize it myself, or is there an inherently thread safe collection?

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 22:29

    Pre .net 4.0 most collections in .Net are not thread safe. You'll have to do some work yourself to handle the synchronization: http://msdn.microsoft.com/en-us/library/573ths2x.aspx

    Quote from article:

    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.

    Sync Root Property
    Lock Statement

    Object thisLock = new Object();
    ......
    lock (thisLock)
    {
        // Critical code section
    }
    

    In .net 4.0 the introduced the System.Collections.Concurrent namespace

    Blocking Collection
    Concurrent Bag
    Concurrent Queue
    Concurrent Dictionary
    Ordable Partitioner
    Partitioner
    Partitioner T

提交回复
热议问题