简体   繁体   English

如何安全地清除ASP.NET缓存线程?

[英]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. 我认为这不是线程安全的-如果某些请求尝试获取缓存的角色,则缓存!= null,同时清除缓存,GetRoles返回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");
}

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

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