开发者

Synchronize Read Write Collection in .NET

I have an object which holds a collection of it开发者_运维知识库ems. 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();
    }
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜