ConcurrentDictionary - AddOrUpdate问题

时间:2015-01-30 08:30:59

标签: c# concurrentdictionary

我使用下面的代码尝试根据字符串更新字典对象中的值。

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

但是UsersessionStatistic中的userViewModel2对象未在ConcurrentDictionary中更新(它的浏览器仍在说"Netscape"),我做错了什么?

1 个答案:

答案 0 :(得分:1)

关于价值工厂,the docs say

  

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

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

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