在ConcurrentDictionary AddOrUpdate中为更新部分添加什么 [英] What to add for the update portion in ConcurrentDictionary AddOrUpdate

查看:915
本文介绍了在ConcurrentDictionary AddOrUpdate中为更新部分添加什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Dictionary重新编写一些代码以使用ConcurrentDictionary.我已经查看了一些示例,但是在实现AddOrUpdate函数时仍然遇到困难.这是原始代码:

I am trying to re-write some code using Dictionary to use ConcurrentDictionary. I have reviewed some examples but I am still having trouble implementing the AddOrUpdate function. This is the original code:

    dynamic a = HttpContext;
    Dictionary<int, string> userDic = this.HttpContext.Application["UserSessionList"] as Dictionary<int, String>;

   if (userDic != null)
   {
      if (useDic.ContainsKey(authUser.UserId))
      {
        userDic.Remove(authUser.UserId);
      }
   }
  else
  {
     userDic = new Dictionary<int,string>();
  }
  userDic.Add(authUser.UserId, a.Session.SessionID.ToString());
  this.HttpContext.Application["UserDic"] = userDic;

我不知道要为更新部分添加什么:

I don't know what to add for the update portion:

userDic.AddOrUpdate(authUser.UserId,
                    a.Session.SessionID.ToString(),
                    /*** what to add here? ***/);

任何指针将不胜感激.

推荐答案

您需要传递Func,如果更新,该值将返回要存储在字典中的值.我想在您的情况下(因为您不区分添加和更新),这将是:

You need to pass a Func which returns the value to be stored in the dictionary in case of an update. I guess in your case (since you don't distinguish between add and update) this would be:

var sessionId = a.Session.SessionID.ToString();
userDic.AddOrUpdate(
  authUser.UserId,
  sessionId,
  (key, oldValue) => sessionId);

Func始终返回sessionId,以便Add和Update设置相同的值.

I.e. the Func always returns the sessionId, so that both Add and Update set the same value.

顺便说一句: MSDN页面上有一个示例.

这篇关于在ConcurrentDictionary AddOrUpdate中为更新部分添加什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆