簡體   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