Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created October 8, 2014 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottoffen/5db16b9bbd9611ce6dbd to your computer and use it in GitHub Desktop.
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
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