ConcurrentDictionary - AddOrUpdate 问题

ConcurrentDictionary - AddOrUpdate issue

我正在使用下面的这段代码来尝试根据其键更新字典对象中的值。

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
};

//第一次添加

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

//尝试更新

        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);

但是 userViewModel2 中的 UsersessionStatistic 对象没有在 ConcurrentDictionary 中更新(浏览器 属性 仍然显示 "Netscape"),我做错了什么?

关于价值工厂,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

这意味着您将现有值传递给它。您需要用新的更新它:

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