paul deter
paul deter

Reputation: 857

Trying to understand how ConcurrentDictionary works

I would like to initialize value to 0 if it does not already exists. Otherwise it should increment existing value.

ConcurrentDictionary<int, int> dic = new ConcurrentDictionary<int, int>();
dic.AddOrUpdate(1, 0, (key, old) => old++);
dic.AddOrUpdate(2, 0, (key, old) => old++);

At this point, dictionary has keys of 1 and 2 with value of 0 each.

        dic.AddOrUpdate(1, 0, (key, old) => old++);

At this point for the key 1 the value should be 1 whereas for key 2 it should be 0, however, both have value of 0. Any idea why?

Upvotes: 1

Views: 865

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

You have a misconception:

dic.AddOrUpdate(1, 0, (key, old) => old++);

At this point for the key 1 the value should be 1

when you use old++ it returns the original value before the modification to be stored. It is as if you did the equivalent of:

dic.AddOrUpdate(1, 0, (key, old) => 
{
    var original = old;
    old = old + 1;
    return original;
});

You want ++old which will return the modified value or just use

dic.AddOrUpdate(1, 0, (key, old) => old + 1);

Upvotes: 5

rducom
rducom

Reputation: 7320

Try this :

dic.AddOrUpdate(1, 0, (key, old) => old + 1);

I think that's because old is a parameter of the Func<>, it cant be modified.

Upvotes: 1

Related Questions