我有一个巨大的XML文档,我必须解析它来生成域对象。ASP.net缓存+单例模式
由于文档很大,我不想每次用户请求时都解析它,但只是第一次,然后将所有对象保存到缓存中。
public List<Product> GetXMLProducts()
{
if (HttpRuntime.Cache.Get("ProductsXML") != null)
{
return (List<Product>)(HttpRuntime.Cache.Get("ProductsXML"));
}
string xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content\\Products.xml");
XmlReader reader = XmlReader.Create(xmlPath);
XDocument doc = XDocument.Load(reader);
List<Product> productsList = new List<Product>();
// Parsing the products element
HttpRuntime.Cache.Insert("ProductsXML", productsList);
return productsList;
}
我如何才能使这个函数在singleton中工作并且是线程安全的?
修正了保存对象到缓存方法(被复制 - 粘贴错误)
如果您从使用会话的页面调用它,而不是从任何其他线程调用该会话,则会话会锁定所有读/写并使其安全。 – Aristos 2012-07-16 10:44:01