Cha*_*ant 7 c# asp.net .net-2.0
只是寻找这段代码的代码审查.ASP.net Cache不是一个选项.静态列表将在每天获得超过10K页面浏览量的网站上进行大量访问,并且可能会进行并发读取尝试.在重建列表时应用程序重新启动我想知道是否有任何问题我可能会忽略?锁定列表是否被实例化最佳实践?
public class MyClass
{
private static List<Entry> _listCache = null;
protected static List<Entry> ListCache
{
get
{
if (_listCache == null)
{
_listCache = new List<Entry>();
lock (_listCache)
{
//Add items to the list _listCache from XML file
}
}
return _listCache;
}
}
//....Other methods that work with the list
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 13
10k视图 - 这是每8秒一个...不确定你需要担心太多... ;-p
但重新编写代码 - 这会使事情过于复杂,你仍然可能最终将其初始化两次.我只是使用静态构造函数来做到这一点; 它会更强大.如果你必须有完全孤立的延迟加载(即使在类型上使用其他静态方法),也有一个内部类来实现相同的技巧:
public class MyClass
{
static class InnerCache {
internal static readonly IList<Entry> _listCache;
static InnerCache() {
List<Entry> tmp = new List<Entry>();
//Add items to the list _listCache from XML file
_listCache = new ReadOnlyCollection<Entry>(tmp);
}
}
protected static IList<Entry> ListCache {
get {return InnerCache._listCache;}
}
}
Run Code Online (Sandbox Code Playgroud)
我也会担心有人改变列表的可能性 - 可能想要使用只读列表!
多个线程可以初始化_listCache。根据代码生成优化和运行时执行优化,这可能会导致多个线程锁定和更新不同的对象。此外,您不能将列表公开为属性,允许任何人添加/删除带有 oa 锁的对象。
您最好使用不可变列表,多个读者可以在只读模式下安全地解析该列表。或者,您可以使用读写锁,但在初始化控制和访问读写控制之间,事情会变得非常棘手。
| 归档时间: |
|
| 查看次数: |
2793 次 |
| 最近记录: |