Is it right to use ConcurrentBag <T> as an object ConcurrentDictionary <key, object>

In the following code:

 public class SomeItem { } public class SomeItemsBag : ConcurrentBag< SomeItem > { } public class SomeItemsList : List< SomeItem > { } public static class Program { private static ConcurrentDictionary< string, SomeItemsBag > _SomeItemsBag; private static ConcurrentDictionary< string, SomeItemsList > _SomeItemsList; private static void GetItem(string key) { var bag = _SomeItemsBag[key]; var list= _SomeItemsList[key]; ... } } 

My assumption is that the bag is thread safe and the list is not. Is this the right way to handle a list dictionary in a multi-threaded application?

Edited to add: Only 1 thread will add to the bag / list and another thread will be deleted, but many threads can access.

+7
source share
1 answer

Your assumptions that ConcurrentBag are thread safe and List are incorrect. But you can synchronize access to the list, for example:

 private static ConcurrentDictionary< string, SomeItemsBag > _SomeItemsBag; private static ConcurrentDictionary< string, SomeItemsList > _SomeItemsList; private static object _someItemsListLocker = new object(); private static void GetItem(string key) { var bag = _SomeItemsBag[key]; lock (_someItemsListLocker) { var list = _SomeItemsList[key]; } } 

However, you'd better describe the situation in full if you want more holistic advice on which data structure you should use. Note that there are also ConcurrentQueue and ConcurrentStack , which might be better for what you want on the list. They are optimized in multi-threaded scenarios, because adding and deleting can be performed only on one side (the same sides for the stack, opposite sides for the queue).

+2
source

All Articles