In the collection type of C #, there are synchronized static methods, and SyncRoot instance methods
For ArrayList and Hashtable collection classes, when thread safety is required, it is best to take advantage of its own property syncroot, although it can be implemented using its synchronized () method, but using properties is better.
Thread-Safe Collections:
BlockingCollection:
A thread-safe collection class that provides thread safety for any type of collection
When to use a thread-safe collection
This article explains the new collection types introduced by. NET Framework4 that are designed to support multi-threaded add and delete operations in five. Unlike the SyncRoot attribute in the collection type in the previous version and the Synchronized () method, 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 a method for manipulating thread-safe collections for use by the product/consumer
For example, see:
Iproducerconsumercollection<t> Interface
The
Official example gives a stack-based thread-safe implementation that he inherits from the interface. Then lock lock to achieve thread safety, the interface has four methods:
[__dynamicallyinvokable] public Span style= "COLOR: #0000ff" >interface iproducerconsumercollection<t>: Ienumerable<t> // Methods [__dynamicallyinvokable] void CopyTo (t[] array, int index); [ __dynamicallyinvokable]t[] ToArray (); [__dynamicallyinvokable] bool TryAdd (T item); [__dynamicallyinvokable] bool TryTake (out In addition to CopyTo methods, the rest of the interface itself, the stack-based thread-safe implementation is the lock, then why not call the SyncRoot property in the stack data structure and the synchronized () method to lock the implementation of synchronization?
Reference:
C # Synchronized and SyncRoot thread-synchronous source code analysis and threaded security access to generic collections
SyncRoot Property
If the call is the SyncRoot property of the collection class, its lock is object-level, and static is type-level. Specific back to the next study.
BlockingCollection type This collection class is interesting, he implements all the methods of iproducerconsumercollection<t>, and can implement thread safety for any custom type. In particular, his timing blocking operations, specific code examples see:
How to: Add and remove items individually in BlockingCollection
BlockingCollection Overview
Thread-Safe collection classes in C #