After reading a couple of notes that it's better not to lock the whole foreach
block, decided to always return a cloned instance of the collection from the enumerator. This is the code that I'm currently using.
https://stackoverflow.com/a/5874474/437393
Then, some code from another thread calls collection.ElementAtOrDefault(collection.Count - 1)
and Clone
method inside of my collection breaks with exception below. Why and how to make it right?
Destination array is not long enough to copy all the items in the collection. Check array index and length
Collection
private static readonly object _indexLock = new object();
...
public IEnumerator<T> GetEnumerator()
{
return Clone().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Clone().GetEnumerator();
}
public List<T> Clone()
{
var copy = new List<T>(_items.Count);
lock (_indexLock)
{
copy = _items.ToList();
//_items.ForEach(o => copy.Add(o));
}
return copy;
}