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) { this.@lock.EnterWriteLock(); try { //do something with item and add it to the collection this.items.Add(item); } finally { this.@lock.ExitWriteLock(); } } public void GoThroughAllItems() { this.@lock.EnterReadLock(); try { foreach (Item item in this.Items) { #if option2 this.@lock.ExitReadLock(); #endif //process item, which may take a long time #if option2 this.@lock.EnterReadLock(); #endif } } #if option2 catch #endif #if option1 finally #endif { this.@lock.ExitReadLock(); } }