繁体   English   中英

需要帮助了解ASP.NET中的锁定

[英]Need help understanding locking in ASP.NET

我在理解锁定多用户/ Web应用程序的基本概念时遇到了一些麻烦。 当用户获得我们的联合会授权时,他将返回用户名声明,然后我们将使用该声明来检索有关他的一些额外信息,如下所示:

var claimsIdentity = (ClaimsIdentity)HttpContext.Current.User.Identity;
if(!claimsIdentity.HasClaim(CustomClaims.UserId)) //If not set, retrieve it from dataBase
{
   //This can take some time
   var userId = retrieveUserId(claimsIdentity.FindFirst(ClaimTypes.NameIdentifier)); 
   //Because the previous call could take some time, it's possible we add the claim multiple time during concurrent requests
   claimsIdentity.AddClaim(new Claim(CustomClaims.UserId, userId));
}

如代码中所示,具有重复的声明并不是我真正想要的,所以我认为我将锁定检查声明是否存在的所有内容:

private static readonly object _authorizeLock = new object();
...
lock(_authorizeLock)
{
   if(!claimsIdentity.HasClaim(CustomClaims.UserId)) //If not set, retrieve it from dataBase
   {
      ...
   }
}

但是,这感觉不对。 此锁不适合所有传入请求吗? 这意味着即使授权用户也已经必须“等待”,即使他们的信息已被检索到也是如此。

有人知道我如何最好地应对吗?

答案1:克服它,住重复的条目。

答案2:如果您打开了会话,则可以通过访问会话存储在同一用户(会话)的请求之间隐式锁定。 只需添加一个假人

Session["TRIGGER_SESSION_LOCKING_DUMMY"] = true

答案3:对由您的Identity索引的对象实施一些自定义锁定。 像这样

lock(threadSafeStaticDictionary[User.Identity.Name]) { ... }

答案4:直接锁定Identity对象(由于重复,应该共享)(尽管不建议这样做)

lock(User.Identity)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM