简体   繁体   中英

Need help understanding locking in ASP.NET

I'm having some trouble understanding the basic concepts of locking in a multi-user / web application. 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.

Answer 2: If you have sessions turned on you get implicit locking between requests from the same user (session) by accessing the session storage. Simply add a dummy

Session["TRIGGER_SESSION_LOCKING_DUMMY"] = true

Answer 3: Implement some custom locking on an object indexed by your 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)

lock(User.Identity)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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