如何清除ASP.. NET缓存线程安全
本文关键字:NET 缓存 线程 安全 ASP 何清除 清除 | 更新日期: 2023-09-27 18:16:10
在我的项目中,我有一些使用单例模式实现的缓存值-它看起来像这样:
Roles GetRoles
{
get{
var cached = HttpContext.Current.Cache["key"];
if(cached == null){
cached = new GetRolesFromDb(...);
}
return cached as Roles;
}
}
当我更改角色时,我正在清除缓存(遍历所有键)。我认为它不是线程安全的-如果一些请求试图获得缓存的角色,
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");
}