ConcurrentDictionary(Of TKey, TValue).GetOrAdd Method

.NET Framework (current version)
 

Adds a key/value pair to the ConcurrentDictionary(Of TKey, TValue) if the key does not already exist.

Namespace:   System.Collections.Concurrent
Assembly:  mscorlib (in mscorlib.dll)

NameDescription
System_CAPS_pubmethodGetOrAdd(TKey, TValue)

Adds a key/value pair to the ConcurrentDictionary(Of TKey, TValue) if the key does not already exist.

System_CAPS_pubmethodGetOrAdd(TKey, Func(Of TKey, TValue))

Adds a key/value pair to the ConcurrentDictionary(Of TKey, TValue) by using the specified function, if the key does not already exist.

The following example shows how to call the GetOrAdd method:

' Imports System.Collections.Concurrent
' Imports System.Threading.Tasks
Class CD_GetOrAddOrUpdate

    ' Demonstrates:
    ' ConcurrentDictionary<TKey, TValue>.AddOrUpdate()
    ' ConcurrentDictionary<TKey, TValue>.GetOrAdd()
    ' ConcurrentDictionary<TKey, TValue>[]
    Shared Sub Main()
        ' Construct a ConcurrentDictionary
        Dim cd As New ConcurrentDictionary(Of Integer, Integer)()

        ' Bombard the ConcurrentDictionary with 10000 competing AddOrUpdates
        Parallel.For(0, 10000,
                       Sub(i)
                           ' Initial call will set cd[1] = 1. 
                           ' Ensuing calls will set cd[1] = cd[1] + 1
                           cd.AddOrUpdate(1, 1, Function(key, oldValue) oldValue + 1)
                       End Sub)

        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
        Dim value As Integer = cd.GetOrAdd(2, Function(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)
    End Sub
End Class
Return to top
Show: