2

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

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

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

4

1 回答 1

1

关于价值工厂,文档说

updateValueFactory 类型:System.Func 用于根据键的现有值为现有键生成新值的函数

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

MyStaticClass.UsersViewModel.AddOrUpdate(userViewModel2.UserSessionStatistic.Id,
                                         userViewModel2, 
                                         (key, oldModel) => userViewModel2);
于 2015-01-30T08:58:26.830 回答