gpt4 book ai didi

c# - 给定单例缓存模式的缺点

转载 作者:行者123 更新时间:2023-11-30 17:06:44 25 4
gpt4 key购买 nike

我正在使用给定的单例模式在 ASP.NET 中缓存类对象。谁能强调这种方法的缺点?

public class CacheManager
{
private static CacheManager _instance;

protected CacheManager(string key) { id = key; }
public static CacheManager getInstance(string key)
{
if (HttpContext.Current.Cache[key] == null)
HttpContext.Current.Cache.Insert(key, _instance = new CacheManger(key), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(120),CacheItemPriority.Default,new CacheItemRemovedCallback(ReportRemovedCallback));

return (CacheManager)HttpContext.Current.Cache[key];
}

private static void ReportRemovedCallback(string CacheManager, object value, CacheItemRemovedReason reason)
{
_instance = null;
}

public string id { get; private set; }
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
}

最佳答案

我看不出有任何理由让您将其设为单例。我只想为每个获取/设置值的属性编写一个包装器。这样您就可以使用 IoC 容器更轻松地注入(inject)它并提高可测试性。

就目前而言,您的代码不是线程安全的,这也可能导致问题。

关于c# - 给定单例缓存模式的缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15248686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com