[Mono-list] How consistent are exceptions?

edward.harvey.mono edward.harvey.mono at clevertrove.com
Wed Feb 13 21:01:18 UTC 2013


> From: Alan [mailto:alan.mcgovern at gmail.com]
> 
> This approach will not work. You may not get an exception, you may
> just end up looping forever inside the dictionary. This is not a
> theoretical issue, it is something which does happen in the wild when
> you mutate a dictionary while iterating it.

Oh crap, thank you for bringing it up...  So I think what you're saying is that I can't rely on the exception at all (nevermind the details of identifying why the exception was raised).  In reality, I simply have to implement some form of locking or inter-thread communication.

So, given that I want the iterating thread to get interrupted, and I don't want to block the writing thread, it means I'm not going to lock() the dictionary.  Even if I use a ConcurrentDictionary, that just means the data all remains intact and no exceptions are thrown; it still doesn't provide any communciation mechanism to signal the iterating thread that any change has occurred.

So I'm thinking, I create a dictionary serial number, and every time I write to the dictionary, I Interlocked.Increment the serial number.  (Or, put the dictionary inside a class that includes an int, and lock() the class to atomically perform the increment and dictionary modification).  That way, my iterating thread can in the beginning detect the value of the serial, and notice the serial has increased while inside the loop, so the iterating thread can then be aware somebody has updated the dictionary.

Is there a better way?


More information about the Mono-list mailing list