May 3rd, 2010, 01:36 PM
ConcurrentDictionary writes and enumeration thread sync.
I'm using between 8-16 threads to write to a .Net 4.0 ConcurrentDictionary collection, and it works great. However I have read that during an enumeration, an update may occur, meaning the enumeration doesn't reflect the full dictionary. I have an enumeration thread which fires every 5 seconds on a timer, to clean, i.e. remove ConcurrentDictionary old items. I want to halt the write/updates to the concurrent dictionary, so the enumerator works as I want.
What would be the best synchronization mechanism for this. I did look at using AutoResetEvent with a timeout, but with the wait and set mechanism potentially waiting for 5 seconds to send the signal to the other 8 threads restart updates.
Any ideas would be helpful. I know the knowledge base for the new .Net 4 TPL is still not that big, so any help would be appreciated.
May 3rd, 2010, 05:20 PM
Re: ConcurrentDictionary writes and enumeration thread sync.
The whole point of ConcurrentDictionary is that multiple threads and read and write simultaenously without any adverse effects. You're saying that you cannot allow multiple readers/writers under all circumstances so this is probably not the datastructure you want to use. You have three options:
1) Wrap all uses of the dictionary in a ReaderWriterLockSlim. For the cases where you want to allow concurrent read/write access you take a 'Read' lock. For the case where you want to do a safe update with no other active threads, use the 'Write' lock.
2) Modify your code so you don't require the enumerator to work a specific way.
3) Use a different datastructure.
I'd recommend 2 myself. It's a concurrent dictionary, writing code which breaks when multiple threads are reading/writing from the dictionary is just crazy. It's like making a 10 lane motorway and saying that you can only use 1 lane.
For all your .NET bittorrent needs
NOTE: My code snippets are just
snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
Tags for this Thread
Click Here to Expand Forum to Full Width