Search code examples
c#multithreadingsynchronizationlockingreaderwriterlockslim

ReaderWriteLockSlim or Lock


I m using ConcurrentBag to store object in run time. At some point I need to empty the bag and store the bag content to a list. This is what i do:

        IList<T> list = new List<T>();

        lock (bag)
        {
            T pixel;

            while (bag.TryTake(out pixel))
            {
                list.Add(pixel);
            }
        }

My Question is with synchronization, As far as I read in the book lock is faster than others synchronization methods. Source -- http://www.albahari.com/threading/part2.aspx.

Performance is my second concern, I d like to know if I can use ReaderWriterLockSlim at this point. What would be the benefit of using ReaderWriterLockSlim? The reason is that, I dont want this operation to block incoming requests.

If yes, Should I use Upgradable Lock?

Any ideas ? Comments?


Solution

  • I'm not sure why you're using the lock. The whole idea behind ConcurrentBag is that it's concurrent.

    Unless you're just trying to prevent some other thread from taking things or adding things to the bag while you're emptying it.

    Re-reading your question, I'm pretty sure you don't want to synchronize access here at all. ConcurrentBag allows multiple threads to Take and Add, without you having to do any explicit synchronization.

    If you lock the bag, then no other thread can add or remove things while your code is running. Assuming, of course, that you protect every other access to the bag with a lock. And once you do that, you've completely defeated the purpose of having a lock-free concurrent data structure. Your data structure has become a poorly-performing list that's controlled by a lock.

    Same thing if you use a reader-writer lock. You'd have to synchronize every access.

    You don't need to add any explicit synchronization in this case. Ditch the lock.