Created
October 8, 2014 19:37
-
-
Save scottoffen/5db16b9bbd9611ce6dbd to your computer and use it in GitHub Desktop.
Creating a custom thread-safe List<T> in C# that supports Add, Remove and Yank
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.Linq; | |
using System.Collections.Generic; | |
namespace SampleNamespace | |
{ | |
class WrappedList<T> | |
{ | |
private List<T> list = new List<T>(); | |
private object sync = new object(); | |
public List<T> Raw | |
{ | |
get | |
{ | |
return list; | |
} | |
} | |
public void Add(T value) | |
{ | |
lock (sync) | |
{ | |
list.Add(value); | |
} | |
} | |
public void Add(List<T> values) | |
{ | |
lock (sync) | |
{ | |
list.AddRange(values); | |
} | |
} | |
public bool Remove(T item) | |
{ | |
lock (sync) | |
{ | |
return list.Remove(item); | |
} | |
} | |
public int Remove(Predicate<T> predicate) | |
{ | |
lock (sync) | |
{ | |
return list.RemoveAll(predicate); | |
} | |
} | |
public T Yank(Func<T, bool> predicate) | |
{ | |
lock (sync) | |
{ | |
T item = list.Where(predicate).First(); | |
if (item != null) | |
{ | |
list.Remove(item); | |
} | |
return item; | |
} | |
} | |
public T Yank(Func<T, int, bool> predicate) | |
{ | |
lock (sync) | |
{ | |
T item = list.Where(predicate).First(); | |
if (item != null) | |
{ | |
list.Remove(item); | |
} | |
return item; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment