Synchronized Collections
SynchronizedList and SynchronizedDictionary synchronized collections.
A synchronized collection is used to wrap a regular list or dictionary and protect it from concurrent access via read-write locks. They are suitable for scenarios such as a small amount of shared state within the framework, cache indexes, registries, descriptor collections, etc.
Type Relationship
SynchronizedList<T>
Thread security list, implementing IList<T> Source, ICollection<T> Source and the non-generic ICollection Source.
SynchronizedDictionary<TKey, TValue>
Thread security dictionary, implements IDictionary<TKey, TValue> Source, and provides a concurrent-style upsert method.
ListUtility
Provides IList<T>.Synchronize() packaging method.
DictionaryExtension
Provides IDictionary<TKey, TValue>.Synchronize() packaging method.
SynchronizedList
SynchronizedList<T> uses read-write locks to protect reads and writes. Read operations enter the read lock, write operations enter the write lock, and the read lock is also maintained during enumeration.
Source: framework/Zongsoft.Core/test/Collections/SynchronizedListTest.cs (excerpt; see source for context).
public void Add()
{
const int COUNT = 1_0000;
var list = new SynchronizedList<int>(COUNT);
Parallel.For(0, COUNT, index =>
{
list.Add(index);
if(index % 100 == 0)
{
foreach(var item in list)
{
Assert.True(item >= 0);
}
for(int i = 0; i < list.Count; i++)
{
Assert.True(list[i] >= 0);
}
}
});
Assert.Equal(COUNT, list.Count);
var hashset = new HashSet<int>(list);
Assert.Equal(COUNT, hashset.Count);
}You can also use extension methods to wrap existing lists.
The packaging entrance of the existing list is ListUtility.Synchronize; after packaging, it should be uniformly accessed through the returned object. If the shared code continues to directly modify the original list, the lock will be bypassed.
A read lock is held when enumerating SynchronizedList<T>. Do not perform operations inside an enumeration loop that may block for a long time, and do not write to the list during the same enumeration.
SynchronizedDictionary
In addition to regular dictionary operations, SynchronizedDictionary<TKey, TValue> also provides TryAdd, GetOrAdd, AddOrUpdate, and TryUpdate methods similar to concurrent dictionaries.
Source: framework/Zongsoft.Core/test/Collections/SynchronizedDictionaryTest.cs (excerpt; see source for context).
GetOrAdd and AddOrUpdate use upgradeable read locks to reduce write lock scope. Keys and Values return snapshot collections to prevent the caller from getting the internal collection view.
Select Suggestions
Requires complete IDictionary<TKey, TValue> Source semantics and conditional updates
Use SynchronizedDictionary<TKey, TValue>.
High-throughput lock-free or fine-grained concurrent dictionary scenarios
Evaluate the .NET official concurrency collection first.
Related Resources
Last updated