Copyright 2008-2009, Paul Jackson, all rights reserved
During my presentation on Parallel Programming in .Net 4.0 at the Orlando Code Camp yesterday, I was asked a question that I didn’t know the answer to and didn’t have time in the session to try out. The question had to do with the new concurrent collections (System.Collections.Concurrent) available in .Net 4.0 and whether their concurrency also enabled us to change the collection while it was being enumerated.
We all know that this is something we can’t do:
At line 11, trying to remove an item from the collection we’re enumerating over results in an InvalidOperationException -- Collection was modified; enumeration operation may not execute.
But an interesting side-effect of the concurrent collections in .Net 4.0 appears to be that this is now possible – obviously because one thread needs to be able to enumerate a concurrent collection while others are adding-to/removing-from. So changing the code to use ConcurrentDictionary:
Results in our being able to enumerate the dictionary and remove each item as we process it.
But what if we want to remove one of the items that hasn’t been processed yet? What if some value in the current item being processed results in our needing to remove a future item?
In this example, when we process the item with a key of 4, we want to remove key 8 from the collection – which also works:
And corollary of this is also true, that if we try to add to the collection while enumerating:
It works as well:
So a special “thank you” to the gentleman in my session yesterday who asked the question. It looks like the answer’s “yes”.