我有一个类,该类以单例形式在旧的asp.net Web表单应用程序中呈现。该类被用作单例,因为它会执行一些我只想在应用程序启动时进行的详尽的文件系统读取。这是一个简化的示例。
public sealed class WidgetService
{
private static object _lock = new object();
private WidgetService()
{
}
public static WidgetService Instance
{
get
{
var cachedInstance = HttpContext.Current.Cache["WidgetService"] as WidgetService;
if (cachedInstance == null)
{
lock (_lock)
{
cachedInstance = HttpContext.Current.Cache["WidgetService"] as WidgetService;
if (cachedInstance == null)
{
cachedInstance = new WidgetService();
HttpContext.Current.Cache["WidgetService"] = cachedInstance;
}
}
}
return cachedInstance;
}
}
private List<Widget> _widgets;
public List<Widget> Widgets
{
get
{
if (_widgets == null)
{
lock (_lock)
{
if (_widgets == null)
{
_widgets = GetWidgetsFromFileSystem();
}
}
}
return _widgets;
}
}
}
这些小部件将通过以下方式在网页中访问:
WidgetService.Instance.Widgets
我的理解是,asp.net中的缓存是线程安全的。那么我是否使用Instance属性中的锁来过度使用它?我可以将属性重写为:
public static WidgetService Instance
{
get
{
return (WidgetService)(HttpContext.Current.Cache["WidgetService"] ?? (HttpContext.Current.Cache["WidgetService"] = new WidgetService()));
}
}
还是有一种更好的方法来处理这样的事情?