C # .NET 4.0 ConcurrentDictionary: TryRemove inside lock?

I believe this works, I tested it with several parallel threads (although not exhaustive for race conditions and dead ends):

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 a continuation of this question:

Is it possible to remove elements from ConcurrentDictionary from the enumeration loop of this dictionary?

And this question:

Updating Value Fields in ConcurrentDictionary

That I am doing two “risky” maneuvers:

  • Removing values ​​from ConcurrentDictionary, while listing through it (which seems to be good).
  • Value ConcurrentDictionary. , , ConcurrentDictionary ( , ).
+5
2

. ( ), .

, - ConcurrentDictionary - , item. : ( ) () , . , -, . , !

, out dump . - TryRemove? , .

+4

, , - , /, , ( , ), , :

 ConcurrentDictionary<string, int> cc = new ConcurrentDictionary<string, int>();

        cc.GetOrAdd("1", 1);

, / .

        cc.AddOrUpdate("1", 2, (a,b) => b + 1);

         var removeSuccess = ((ICollection<KeyValuePair<string, int>>)cc).Remove(
    new KeyValuePair<string, int>("1", 1));

, "1", , .

. : http://thargy.com/2012/09/the-hidden-secret-of-the-concurrent-dictionary/ http://blogs.msdn.com/b/pfxteam/archive/2011/04/02/10149222.aspx

0

All Articles