ConcurrentDictionary writes and enumeration thread sync.
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: ConcurrentDictionary writes and enumeration thread sync.

  1. #1
    Join Date
    May 2010
    Posts
    1

    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.

    Bob.

  2. #2
    Join Date
    May 2007
    Posts
    1,546

    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.
    www.monotorrent.com 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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center