简体   繁体   中英

How to clear ASP.NET cache thread-safely?

In my project I have some cached values implemented using singleton pattern - it looks like this:

Roles GetRoles
{
get{
         var cached = HttpContext.Current.Cache["key"];
         if(cached == null){
             cached = new GetRolesFromDb(...);
         }
         return cached as Roles;
   }
}    

When I change the roles I'm clearing the cache (iterating over all keys). I think it isn't thread-safe - if some request tries to get cached roles, cached != null and meanwhile cache had been cleared GetRoles returns null.

private object lockRoles = new object();

public Roles GetRoles
{
  get 
  {
    object cached = HttpContext.Current.Cache["key"];
    if(cached == null) 
    {
      lock(lockRoles)
      {
        cached = HttpContext.Current.Cache["key"];
        if (cached == null) 
        {
          cached = new GetRolesFromDb(...);
          HttpContext.Current.Cache["key"] = cached; 
        }
      }
    }
    return (Roles)cached;
  }
}    

public void ClearRoles()
{
  HttpContext.Current.Cache.Remove("key");
}

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