ConcurrentDictionary<TKey, TValue>.AddOrUpdate Method

Adds a key/value pair to the ConcurrentDictionary<TKey, TValue> if the key does not already exist, or updates a key/value pair in the ConcurrentDictionary<TKey, TValue> if the key already exists.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  Name Description
Public method AddOrUpdate(TKey, Func<TKey, TValue>, Func<TKey, TValue, TValue>) Uses the specified functions to add a key/value pair to the ConcurrentDictionary<TKey, TValue> if the key does not already exist, or to update a key/value pair in the ConcurrentDictionary<TKey, TValue> if the key already exists.
Public method AddOrUpdate(TKey, TValue, Func<TKey, TValue, TValue>) Adds a key/value pair to the ConcurrentDictionary<TKey, TValue> if the key does not already exist, or updates a key/value pair in the ConcurrentDictionary<TKey, TValue> by using the specified function if the key already exists.
Top

The following example shows how to call the AddOrUpdate method:

class CD_GetOrAddOrUpdate
{
    // Demonstrates: 
    //      ConcurrentDictionary<TKey, TValue>.AddOrUpdate() 
    //      ConcurrentDictionary<TKey, TValue>.GetOrAdd() 
    //      ConcurrentDictionary<TKey, TValue>[] 
    static void Main()
    {
        // Construct a ConcurrentDictionary
        ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>();

        // Bombard the ConcurrentDictionary with 10000 competing AddOrUpdates
        Parallel.For(0, 10000, i =>
        {
            // Initial call will set cd[1] = 1.   
            // Ensuing calls will set cd[1] = cd[1] + 1
            cd.AddOrUpdate(1, 1, (key, oldValue) => oldValue + 1);
        });

        Console.WriteLine("After 10000 AddOrUpdates, cd[1] = {0}, should be 10000", cd[1]);

        // Should return 100, as key 2 is not yet in the dictionary 
        int value = cd.GetOrAdd(2, (key) => 100);
        Console.WriteLine("After initial GetOrAdd, cd[2] = {0} (should be 100)", value);

        // Should return 100, as key 2 is already set to that value 
        value = cd.GetOrAdd(2, 10000);
        Console.WriteLine("After second GetOrAdd, cd[2] = {0} (should be 100)", value);
    }
}
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft