In reply to all of the answers since my original one:
People found these solutions:
- use SynchronizedCollection - the source code is almost identical to the SynchronizedList below, with the same features and issues
- use ArrayList.Synchronized - this will return a SyncIList, which is the same thing as the SynchronizedList below, only not generic
- using a thread safe form of a list, where on every access you clone it - I believe the implementation presented could be improved significantly using ThreadLocal or AsyncLocal, but it would still fail any performance tests
- use various combinations of classes in the Collections.Concurrent namespace - these contains some good options for ICollection, but NOT for IList for index access
- use a ConcurrentDictionary<int, T>, with indexes as keys, to emulate an IList - this is one of the best ideas I've seen, but it's not really in the spirit of an IList, which implies O(1) index read/append complexity and some complexity in insert/deletes, as well as an O(n) space complexity. Also, what about IndexOf and sorting operations?
Most complaints against the SynchronizedList class were related to:
- slowness of the lock mechanism - the performance calculation varies wildly based on the scenario where the list is used, so this is a valid option for a vague requirement
- using lock(object) and not using SemaphoreSlim - OK, this is my complaint :) but fixing the code to use it is trivial
A more complex system of locks can be implemented, like for individual rows, groups of rows, etc. That will start to look like implementing your own database, though. Writing a high performance collection is an art and is very tightly coupled to the specific scenario you want to use it in.
I still believe that for a general use scenario the simple solution here is the most versatile.
The C5 collection library, which is one of the inspirations for great collection design, handles concurrency thus:
- no concurrent collections (by design) because they feel a simple lock mechanism can be implemented, but scenarios get very complex when multiple collections are getting accessed at the same time
- "A tree-based collection can be safely enumerated while modifying it" - where they recommend "pattern 66": "one can take a snapshot of the tree and then enumerate the items of that snapshot, while modifying the original tree at the same time"
Original answer:
If you look at the source code for List of T (https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,c66df6f36c131877) you will notice there is a class there (which is of course internal - why, Microsoft, why?!?!) called SynchronizedList of T. I am copy pasting the code here:
[Serializable()]
internal class SynchronizedList : IList<T> {
private List<T> _list;
private Object _root;
internal SynchronizedList(List<T> list) {
_list = list;
_root = ((System.Collections.ICollection)list).SyncRoot;
}
public int Count {
get {
lock (_root) {
return _list.Count;
}
}
}
public bool IsReadOnly {
get {
return ((ICollection<T>)_list).IsReadOnly;
}
}
public void Add(T item) {
lock (_root) {
_list.Add(item);
}
}
public void Clear() {
lock (_root) {
_list.Clear();
}
}
public bool Contains(T item) {
lock (_root) {
return _list.Contains(item);
}
}
public void CopyTo(T[] array, int arrayIndex) {
lock (_root) {
_list.CopyTo(array, arrayIndex);
}
}
public bool Remove(T item) {
lock (_root) {
return _list.Remove(item);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
lock (_root) {
return _list.GetEnumerator();
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
lock (_root) {
return ((IEnumerable<T>)_list).GetEnumerator();
}
}
public T this[int index] {
get {
lock(_root) {
return _list[index];
}
}
set {
lock(_root) {
_list[index] = value;
}
}
}
public int IndexOf(T item) {
lock (_root) {
return _list.IndexOf(item);
}
}
public void Insert(int index, T item) {
lock (_root) {
_list.Insert(index, item);
}
}
public void RemoveAt(int index) {
lock (_root) {
_list.RemoveAt(index);
}
}
}
Personally I think they knew a better implementation using SemaphoreSlim could be created, but didn't get to it.
IList<T>
(vsList<T>
)?List<T>
implements? If yes, then could you please provide an interface that you need instead of asking about everything thatList<T>
already have?