When to use ReaderWriterLockSlim and When to use ConcurrentBag?

664 views Asked by At

Is it the same if I used ConcurrentBag (to handle scenario of one writer & multiple readers) instead of using ReaderWriterLockSlim on a List<> ??

UPDATE 1:
The scenario is that there are multiple threads that can reach a static list and some may need to read others may need to write, what I want is:
1- Allow only one thread to add\edit\delete from the list while there are no other threads trying to adding\editing\deleting on it.
2- Allow many threads to read from it at the same time if there's no thread adding\editing\deleting.

1

There are 1 answers

8
Yosef O On BEST ANSWER

In your scenario it sounds like you should be using a ReaderWriterLockSlim on a list.

A concurrent bag does not support deleting (at all) and editing is not safe. Locking a list with a ReaderWriterLockSlim will allow safe deletion and will allow safe editing provided the editing is done within the write lock scope.

Even though both constructs are related to synchronization and threading they are definitely not interchangeable.

  • ConcurrentBag is a collection which you can add, take, peek and (most importantly) enumerate in a thread safe way.
  • ReaderWriterLockSlim is a synch object which allows to read lock or write lock on whatever you want.