I have the following code and wonder if it is thread safe. I only block when I add or remove items from the collection, but I don't block when I iterate over the collection. Locking during an iteration will greatly affect performance, as the collection potentially contains hundreds of thousands of items. Any tips what to do to make this chain safe?
thank
public class Item
{
public string DataPoint { get; private set; }
public Item(string dataPoint)
{
DataPoint = dataPoint;
}
}
public class Test
{
private List<Item> _items;
private readonly object myListLock = new object();
public Test()
{
_items = new List<Item>();
}
public void Subscribe(Item item)
{
lock (myListLock)
{
if (!_items.Contains(item))
{
_items.Add(item);
}
}
}
public void Unsubscribe(Item item)
{
lock (myListLock)
{
if (_items.Contains(item))
{
_items.Remove(item);
}
}
}
public void Iterate()
{
foreach (var item in _items)
{
var dp = item.DataPoint;
}
}
}
EDIT
I was curious to profile performance again between iteration, which is not locked against iteration inside locking on myListLock, and the performance overhead for locking iteration of more than 10 million items was actually minimal.
source