Skip to content

Instantly share code, notes, and snippets.

@alanmcgovern
Created February 14, 2013 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanmcgovern/e7fb05c07d6bb84b2595 to your computer and use it in GitHub Desktop.
Save alanmcgovern/e7fb05c07d6bb84b2595 to your computer and use it in GitHub Desktop.
var dictionary = GetTheDictionary ();
IEnumerator e = dictionary.GetEnumerator ();
object current_dictionary_value;
while (true) {
lock (dictionary) {
try {
if (!e.MoveNext ())
break; // we're at the end of the dictionary
current_dictionary_value = e.current;
} catch {
// An exception here means that the dictionary changed while we were iterating
break;
}
}
// Now we're outside of the lock, do our complex thing
PerformTask (current_dictionary_value);
}
// When adding items to the dictionary, or modifying it in any way, lock it first and you sohuld be safe
lock (dictionary)
dictionary.Add ("key", new object ());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment