Question

i am using Visual Studio 2010 C++ Express and i mant to add an item to my ConcurrentDictionary:

i have such code:

String^ key = gcnew String("key");
int value = 123;
myDictionary->AddOrUpdate(key,value,/*WHAT TO ADD HERE?*/);

AddOrUpdate Method takes 3 argument, not like normal Dictionary 2.

Microsoft sites says it takes such arguments:

public:
TValue AddOrUpdate(
TKey key, 
TValue addValue, 
Func<TKey, TValue, TValue>^ updateValueFactory
)

on microsoft sites i also found code in C#:

cd.AddOrUpdate(1, 1, (key, oldValue) => oldValue + 1);

but it does not work in C++. what i must put as 3rd argument?

Was it helpful?

Solution

The third parameter is a delegate, which in the C# sample code you found is a lambda. However C++/CLI does not support lambdas, so you'd have to do it with a standalone method.

static int UpdateFunc(String^ key, int value)
{
    return value + 1;
}

cd->AddOrUpdate("foo", 1, gcnew Func<String^, int, int>(MyClass::UpdateFunc));

However, you said "I want to add an item to my ConcurrentDictionary". There's no simple "add" method, because it's always the case that other thread may have modified the ConcurrentDictionary. Therefore, there are a couple choices for how to put stuff in the dictionary.

  • AddOrUpdate: Add a value, or modify an existing value if that key already exists. (Passes the current value to a delegate, which returns the modification.)
  • GetOrAdd: Add a value, or retrieve the existing value if that key already exists. (Doesn't modify the dictionary if the key already exists.)
  • this[] (Indexer, uses square brackets): Add a value, or replace the existing value with a constant value.

If all you want is a simple 'add', it's probably the square brackets you're interested in.

cd["foo"] = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top