Created
April 19, 2012 18:11
-
-
Save jchadwick/2422722 to your computer and use it in GitHub Desktop.
Thread-safe List (ConcurrentList<T>)
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; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Linq; | |
public class ConcurrentList<T> : ICollection<T> | |
{ | |
private readonly ConcurrentDictionary<T, object> _store; | |
public ConcurrentList(IEnumerable<T> items = null) | |
{ | |
var prime = (items ?? Enumerable.Empty<T>()).Select(x => new KeyValuePair<T, object>(x, null)); | |
_store = new ConcurrentDictionary<T, object>(prime); | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return _store.Keys.GetEnumerator(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
public void Add(T item) | |
{ | |
if(_store.TryAdd(item, null) == false) | |
throw new ApplicationException("Unable to concurrently add item to list"); | |
} | |
public void Clear() | |
{ | |
_store.Clear(); | |
} | |
public bool Contains(T item) | |
{ | |
return _store.ContainsKey(item); | |
} | |
public void CopyTo(T[] array, int arrayIndex) | |
{ | |
_store.Keys.CopyTo(array, arrayIndex); | |
} | |
public bool Remove(T item) | |
{ | |
return _store.Keys.Remove(item); | |
} | |
public int Count | |
{ | |
get { return _store.Count; } | |
} | |
public bool IsReadOnly | |
{ | |
get { return _store.Keys.IsReadOnly; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment