Thread security collection class in C,
All the set types of C # Have the Synchronized static method and the SyncRoot instance method.
For ArrayList and Hashtable collection classes, it is best to use its built-in attribute SyncRoot to achieve thread security, although it can also be implemented using its Synchronized () method, however, it is better to use attributes.
Thread security set:
BlockingCollection:
A thread security collection class that provides thread security for any type of collection
When to use thread security set
This article explains the five Collection types newly introduced by. net framework4 that specifically support multi-threaded addition and deletion operations. Different from SyncRoot attributes and Synchronized () methods in the previous integration types, these new types use efficient locking and lock-free synchronization mechanisms.
ConcurrentQueue (T)
ConcurrentStack (T)
ConcurrentDictionary (TKey, TValue)
ConcurrentBag (T)
BlockingCollection (T)
IProducerConsumerCollection <T>
Defines a set of Operation thread security methods for products/users.
For example, see:
IProducerConsumerCollection <T> Interface
The official example provides a stack-based thread security implementation that inherits from this interface. Then lock the lock to implement thread security. This interface has four methods:
[_ 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);} except for CopyTo, all the other methods are the interface itself. stack-based thread security implementation is locking, why not call the SyncRoot attribute and Synchronized () in the stack data structure () How to lock to implement synchronization?
Refer:
C # Synchronized and SyncRoot implement source code analysis for thread synchronization and thread security access for generic Sets
SyncRoot attributes
If you call the SyncRoot attribute of the Collection class, the lock is at the object level, while static is at the type level. Let's look back at the details.
BlockingCollection is an interesting collection class. It implements all methods of IProducerConsumerCollection <T> to implement thread security of any custom type. In particular, his timing blocking operations. For specific code examples, see:
How to: Add and retrieve items one by one in BlockingCollection
BlockingCollection Overview