views:

32

answers:

2

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]();
    }
}
A: 

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:

read lock
   foreach oldColl
      populate newColl
exit lock

   foreach newColl
      do things

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.

Andrey
Thanks, but, in general, I think the copy may be too expensive to consider.
Ricardo Peres
@Ricardo Peres expensive in terms of what?
Andrey
In terms of having to copy N elements from one side to the other, of course.
Ricardo Peres
A: 

I would simply choose your first option with the read region around the foreach since multiple threads are allowed in the read block it does not matter that it is rather slow. The exclusive write operation on the other hand is quite fast. So that should be a good solution.

Bernd