Export (0) Print
Expand All

ConcurrentDictionary(Of TKey, TValue).GetOrAdd Method

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

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 GetOrAdd(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.
Public method GetOrAdd(TKey, TValue) Adds a key/value pair to the ConcurrentDictionary(Of TKey, TValue) if the key does not already exist.
Top

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
Show:
© 2014 Microsoft