c# - Is the following thread safe? -
i have following code , wonder whether thread safe. lock when add or remove items collection not lock when iterate on collection. locking while iterating severely impact performance because collection potentially contains hundreds of thousands of items. advice make thread safe?
thanks
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 curious , again profiled performance between iteration not locked vs iterating inside lock on mylistlock , performance overhead of locking iteration on 10 million items quite minimal.
no, isn't thread safe, because collection modified while inside it... do:
item[] items; lock (mylistlock) { items = _items.toarray(); } foreach (var item in items) { var dp = item.datapoint; } so duplicate collection inside lock before cycling on it. use memory (because have duplicate list<>) (concurrentbag<>.getenumerator() this)
note works if item thread safe (for example because immutable)
Comments
Post a Comment