[Mono-list] How consistent are exceptions?
alan.mcgovern at gmail.com
Thu Feb 14 01:34:01 UTC 2013
You could do it with a ConcurrentDictionary and a 'serial' as you've
described. ConcurrentDictionary makes it safe for you to read and
write simultaenously, the serial lets you bail out of your iteration
when the dictionary is modified.
Another alternative is to clone the entire dictionary every time you
want modify it and then you can just replace the old one with the new
modified one. You can bail out of your iteration if the dictionary
you're iterating over is not the same as the current one. However if
the dictionary is large and changes are frequent, this might use a lot
Finally, you can use locking and hope for the best. You could do
something like https://gist.github.com/alanmcgovern/e7fb05c07d6bb84b2595
On 13 February 2013 21:01, edward.harvey.mono
<edward.harvey.mono at clevertrove.com> wrote:
>> 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