Thread-safe collection classes in C#

In C#'s collection types, there are Synchronized static methods, and SyncRoot instance methods


For ArrayList and Hashtable collection classes, when thread safety is required, it is best to use its own property SyncRoot to do it, although it can also be achieved by its Synchronized() method, but it is better to use properties.

Thread-safe collections:
BlockingCollection:
A thread-safe collection class that provides thread safety for any type of collection

When to use thread-safe collections 
This article explains five new collection types introduced in .NET framework 4 that are designed to support multithreaded add and delete operations. Unlike the SyncRoot property and the Synchronized() method in the collection types of previous versions, these new types use an efficient locking and lock-free synchronization mechanism

ConcurrentQueue(T)
ConcurrentStack(T)
ConcurrentDictionary(TKey, TValue)
ConcurrentBag(T)
BlockingCollection(T)

IProducerConsumerCollection<T>
defines methods for manipulating thread-safe collections for production/consumer use

For example see:
IProducerConsumerCollection<T> Interface

The official example gives a stack-based thread-safe implementation, which inherits from this interface. Then lock lock to achieve thread safety. This interface has four methods:

copy code
[__DynamicallyInvokable]
public interface IProducerConsumerCollection<T> : IEnumerable<T>, ICollection, IEnumerable
{
// Methods
[__DynamicallyInvokable]
void CopyTo(T[] array, int index);
[__DynamicallyInvokable]
T[] ToArray();
[__DynamicallyInvokable]
bool TryAdd(T item);
[__DynamicallyInvokable]
bool TryTake(out T item);
}In addition to the methods of CopyTo, the rest are the interface itself. The thread-safe implementation based on the stack is locking, so why not call the SyncRoot attribute and the Synchronized() method in the stack data structure to lock and achieve synchronization?
copy code

Reference:
C# Synchronized and SyncRoot implement thread synchronization source code analysis and thread-safe access to the
SyncRoot property of generic collections

If the SyncRoot property of the collection class is called, the lock is at the object level, while static is at the type level. Go back and study in detail.

This collection class of BlockingCollection type is quite interesting. It implements all the methods of IProducerConsumerCollection<T> and can achieve thread safety of any custom type. Especially his timing blocking operation, please see the specific code example:
How to: Add and remove items one by one in
BlockingCollection Overview of BlockingCollection

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325107406&siteId=291194637