Skip to content

Instantly share code, notes, and snippets.

@devcfgc
Created August 4, 2017 04:41
Show Gist options
  • Save devcfgc/70da477e03607f85968b7ca2d6c9dc16 to your computer and use it in GitHub Desktop.
Save devcfgc/70da477e03607f85968b7ca2d6c9dc16 to your computer and use it in GitHub Desktop.
Thread Safe List in C#
##https://stackoverflow.com/questions/5874317/thread-safe-listt-property
public class ThreadSafeList<T> : IList<T>
{
protected List<T> _interalList = new List<T>();
// Other Elements of IList implementation
public IEnumerator<T> GetEnumerator()
{
return Clone().GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Clone().GetEnumerator();
}
protected static object _lock = new object();
public List<T> Clone()
{
List<T> newList = new List<T>();
lock (_lock)
{
_interalList.ForEach(x => newList.Add(x));
}
return newList;
}
}
## https://stackoverflow.com/questions/9995266/how-to-create-a-thread-safe-generic-list
class MyList<T> {
private List<T> _list = new List<T>();
private object _sync = new object();
public void Add(T value) {
lock (_sync) {
_list.Add(value);
}
}
public bool Find(Predicate<T> predicate) {
lock (_sync) {
return _list.Find(predicate);
}
}
public T FirstOrDefault() {
lock (_sync) {
return _list.FirstOrDefault();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment