I believe this works, I've tested it with multiple concurrent threads (not exhaustively though for race conditions and deadlocks):
public static System.Collections.Concurrent.ConcurrentDictionary<string, item> dict =
new System.Collections.Concurrent.ConcurrentDictionary<string, item>();
public static item dump;
...
foreach (System.Collections.Generic.KeyValuePair<string, item> x in dict)
{
lock (x.Value)
{
if (x.Value.IsCompleted)
{
dict.TryRemove(x.Key, out dump);
}
}
}
This question is sort of a continuation of this question:
And this question:
http://stackoverflow.com/questions/2901289/updating-fields-of-values-in-a-concurrentdictionary
In that I'm doing two "dicey" maneuvers:
- Removing values from a ConcurrentDictionary while at the same time enumerating through it (which seems to be ok).
- Locking the Value portion of a ConcurrentDictionary. Necessary because manipulating fields of the value is not thread safe, only manipulating the values themselves of the ConcurrentDictionary is thread safe (the code above is a snippet of a larger code block in which fields of values are actually manipulated).