I have an object which holds a collection of items. I want to be able to add items to the collection through an AddItem method and also to go through all of the items in the collection. My object must be thread safe. I am using a ReaderWriterLockSlim to assure proper synchronization. How should I synchronize the GoThroughAllItems method? Should I just start a big ReadLock throughout its entire duration, which may be very long, or should I release the lock for each item fetched from the collection, and re-acquire the lock again for the next one?
Here is some sample code:
private ReaderWriterLockSlim @lock = new ReaderWriterLockSlim(); private List items = new List(); public void AddItem(Item item) { [email protected](); try { //do something with item and add it to the collection this.items.Add(item); } finally { [email protected](); } } public void GoThroughAllItems() { [email protected](); try { foreach (Item item in this.Items) { #if option2 [email protected](); #endif //process item, which may take a long time #if option2 [email protected](); #endif } } #if option2 catch #endif #if option1 finally #endif { [email protected](); } }
The best way here is to create a copy of collection, then iterate over it. It has significant memory overhead (but it will be released soon after).
Pseudo code:
and you code with locks per item will not work, because other thread might modify collection and it will cause error, because foreach doesn't allow modification of collections.