user3228992
user3228992

Reputation: 1373

ConcurrentDictionary - AddOrUpdate issue

I'm using this code below to try to update the values in a dictionary object depending on its key.

public static ConcurrentDictionary<string, SingleUserStatisticsViewModel> UsersViewModel = new ConcurrentDictionary<string, SingleUserStatisticsViewModel>();

var userSession = new UserSessionStatistic()
{
    Id = "12345", Browser = "Netscape"
};
var userViewModel = new SingleUserStatisticsViewModel()
{
    UserSessionStatistic = userSession,
    StartTime = DateTime.Now
};

//Add first time

MyStaticClass.UsersViewModel.AddOrUpdate(userViewModel.UserSessionStatistic.Id, userViewModel, (key, model) => model);

//try to Update

        var userSession2 = new UserSessionStatistic()
        {
            Id = "12345",
            Browser = "not getting updated????"
        };
        var userViewModel2 = new SingleUserStatisticsViewModel()
        {
            UserSessionStatistic = userSession2,
            StartTime = DateTime.Now
        };

MyStaticClass.UsersViewModel.AddOrUpdate(userViewModel2.UserSessionStatistic.Id, userViewModel2, (key, model) => model);

But the UsersessionStatistic object in userViewModel2 is not getting updated in the ConcurrentDictionary (it's Browser propery still says "Netscape"), what am I doing wrong?

Upvotes: 2

Views: 787

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

About the value factory, the docs say:

updateValueFactory Type: System.Func The function used to generate a new value for an existing key based on the key's existing value

Which means your passing it the existing value. You need to update it with the new one instead:

MyStaticClass.UsersViewModel.AddOrUpdate(userViewModel2.UserSessionStatistic.Id,
                                         userViewModel2, 
                                         (key, oldModel) => userViewModel2);

Upvotes: 1

Related Questions