gpt4 book ai didi

c# - ConcurrentDictionary - AddOrUpdate 问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:11:51 26 4
gpt4 key购买 nike

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

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"),这是什么我做错了吗?

最佳答案

关于值(value)工厂,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);

关于c# - ConcurrentDictionary - AddOrUpdate 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28231986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com