Search code examples
c#.netmultithreadinglockingblockingcollection

What is better and why to use List as thread safe: BlockingCollection or ReaderWriterLockSlim or lock?


I have System.Collections.Generic.List _myList and many threads can read from it or add items to it simultaneously. From what I've read I should using 'BlockingCollection' so this will work. I also read about ReaderWriterLockSlim and lock, but I don't figure out how to use them instead of BlockingCollection, so my question is can I do the same with:

  1. ReaderWriterLockSlim
  2. lock

instead of using 'BlockingCollection'. If YES, can you please provide simple example and what pros and cons of using BlockingCollection, ReaderWriterLockSlim, lock?

UPDATED readers will be much more than writers!


Solution

  • ReaderWriterLockSlim:

    • is optimized for use cases, when reads from resourse occur more frequently, than writes;
    • can work with any type of resources (not only collections), because it's just a hybrid synchronization construct.

    lock:

    • is a general purpose, rather simple, hybrid synchronization construct without any optimizations; thus, can make performance worse;
    • is a C# wrapper around Monitor class;
    • can work with any type of resources;

    BlockingCollection:

    • is a specific type of collection (concrete type of resource), that oriented to solve 'producer-consumer' tasks;
    • supports timeouts and cancellation mechanism (via cancellation tokens), which makes easier integration into code, which uses TPL.

    I think, your choice is BlockingCollection (if you really have many readers and writers).