简体   繁体   English

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

[英]Need help understanding locking in ASP.NET

I'm having some trouble understanding the basic concepts of locking in a multi-user / web application. 我在理解锁定多用户/ Web应用程序的基本概念时遇到了一些麻烦。 When a user gets authorized by our federation, he'll return with a username claim, which we'll then use to retrieve some extra info about him like so: 当用户获得我们的联合会授权时,他将返回用户名声明,然后我们将使用该声明来检索有关他的一些额外信息,如下所示:

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

As indicated in the code, having duplicate claims isn't really what I'm looking for, so I thought I'd lock everything around the check whether the claim exists or not: 如代码中所示,具有重复的声明并不是我真正想要的,所以我认为我将锁定检查声明是否存在的所有内容:

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

However, this doesn't feel right. 但是,这感觉不对。 Wouldn't this lock be for all incoming requests? 此锁不适合所有传入请求吗? This would mean that even authorized users would still have to "wait", even though their info has already been retrieved. 这意味着即使授权用户也已经必须“等待”,即使他们的信息已被检索到也是如此。

Does anybody have an idea how I could best deal with this? 有人知道我如何最好地应对吗?

Answer 1: Get over it and live with duplicate entries. 答案1:克服它,住重复的条目。

Answer 2: If you have sessions turned on you get implicit locking between requests from the same user (session) by accessing the session storage. 答案2:如果您打开了会话,则可以通过访问会话存储在同一用户(会话)的请求之间隐式锁定。 Simply add a dummy 只需添加一个假人

Session["TRIGGER_SESSION_LOCKING_DUMMY"] = true

Answer 3: Implement some custom locking on an object indexed by your Identity. 答案3:对由您的Identity索引的对象实施一些自定义锁定。 Something like this 像这样

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

Answer 4: Lock on the Identity object directly (which should be shared since you get duplicates) (though it is not recommended) 答案4:直接锁定Identity对象(由于重复,应该共享)(尽管不建议这样做)

lock(User.Identity)

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

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