Search code examples
c#concurrentdictionaryconcurrent-collections

What to add for the update portion in 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? ***/);

Any pointers would be appreciated.


Solution

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

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

    BTW: there is a sample on the MSDN page.