Last active
January 12, 2021 12:12
-
-
Save KaiserWerk/e7c3ff7268bd9167a88bceec13966ca7 to your computer and use it in GitHub Desktop.
C' Example Concurrent Collection Implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace ConcurrencyTests | |
{ | |
public class ConcurrentList<T> | |
{ | |
private List<T> internalList = new List<T>(); | |
private object listLock = new object(); | |
public T this[int i] | |
{ | |
get | |
{ | |
lock (this.listLock) | |
{ | |
T item = this.internalList.FirstOrDefault(e => object.Equals(e, this.internalList[i])); | |
if (item == null) | |
throw new IndexOutOfRangeException("An element with this index does not exist."); | |
return item; | |
} | |
} | |
} | |
public void Add(T item) | |
{ | |
lock (this.listLock) | |
{ | |
this.internalList.Add(item); | |
} | |
} | |
public void AddRange(IEnumerable<T> itemsToAdd) | |
{ | |
lock (this.listLock) | |
{ | |
this.internalList.AddRange(itemsToAdd); | |
} | |
} | |
public long Count() | |
{ | |
lock (this.listLock) | |
{ | |
return this.internalList.Count(); | |
} | |
} | |
public void Clear() | |
{ | |
lock (this.listLock) | |
{ | |
this.internalList.Clear(); | |
} | |
} | |
public ConcurrentList<T> Clone() | |
{ | |
lock (this.listLock) | |
{ | |
var l = new ConcurrentList<T>(); | |
l.AddRange(this.internalList); | |
return l; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wonder if this would work as expected...