Which is preferred in a multi-threaded application: Dictionary with lock object or Concurrency Dictionary
Which is efficient and why should I use one or the other?
edit 1: Storing Guid as key and bool as value.
edit 2: more than 2 worker threads and one UI thread.
I would say you've got the following options.
Some new Framework 4.0 classes:
All new 4.0 classes work faster but have some features mentioned by levanovd. Performance comparison of these classes you can find here.
Some classic solutions from earlier versions:
If I had a restriction of using Framework v3.5, I would use Dictionary + ReaderWriterLock or ReaderWriterLockSlim.
Read carefully about ConcurrentDictionary. It has some unobvious features.
Here are some of them:
AddOrUpdate
there's no guarantees about which of factory delegates will be called and even no guarantee that if a factory delegate will produce some item that this item will be stored in dictionary.GetEnumerator
call is not a snapshot and may be modified during enumeration (that doesn't cause any exceptions).Keys
and Values
properties are snapshots of corresponding collections and may not correspond to actual dictionary state.So please read about ConcurrentDictionary again and decide if this behavior is what you need.
Hope this helps!
When you are implementing a dictionary with a lock object, your main concern seems like thread safety. So it seems, a concurrentDictionary already manages this concern. I think there is no point in re-inventing the wheel.
I think both will provide thread-safety but using a Dictionary with lock object will limit the number of thread that can access the Dictionary concurrently to 1. While using Concurrent Dictionary, you can specify concurrent level (i.e. number of threads that can access the Dictionary concurrently). If performance does matter, I believe Concurrent Dictionary should be your choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With