加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.net缓存单例模式

发布时间:2020-12-16 03:58:37 所属栏目:asp.Net 来源:网络整理
导读:我有一个巨大的 XML文档,我必须解析它以生成域对象. 因为文档很大,我不想在每次用户请求时解析它,而只是第一次,然后将所有对象保存到缓存中. public ListProduct GetXMLProducts(){ if (HttpRuntime.Cache.Get("ProductsXML") != null) { return (ListProduc
我有一个巨大的 XML文档,我必须解析它以生成域对象.

因为文档很大,我不想在每次用户请求时解析它,而只是第一次,然后将所有对象保存到缓存中.

public List<Product> GetXMLProducts()
{
    if (HttpRuntime.Cache.Get("ProductsXML") != null)
    {
        return (List<Product>)(HttpRuntime.Cache.Get("ProductsXML"));
    }

    string xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"ContentProducts.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;
}

如何使这个函数在单例中工作并且是线程安全的最佳方法是什么?

修复了将对象保存到缓存方法(是一个复制粘贴错误)

解决方法

创建一个Lazy静态并在内存中保留应用程序的生命周期.并且不要忘记“真正的”部分,这就是它使线程安全的原因.

public static readonly Lazy<List<Product>> _product = new Lazy<List<Products>>(() => GetProducts(),true);

要将其添加到模型中,只需将其设为私有并返回_product.Value;

public MyModel
{
    ... bunch of methods/properties

    private static readonly Lazy<List<Product>> _products = new Lazy<List<Products>>(() => GetProducts(),true);

    private static List<Product> GetProducts()
    {
        return DsLayer.GetProducts();

    }

    public List<Product> Products { get { return _products.Value; } }
}

要使用Lazy<>创建单例,请使用此模式.

public MyClass
{
    private static readonly Lazy<MyClass> _myClass = new Lazy<MyClass>(() => new MyClass(),true);

    private MyClass(){}

    public static MyClass Instance { get { return _myClass.Value; } }
}

Update/Edit:

在上下文中使用的另一种惰性模式(即Session)

在Session中保存的一些模型:

public MyModel
{
   private List<Product> _currentProducts = null;
   public List<Product> CurrentProducts 
   {
      get
      {
         return this._currentProducts ?? (_currentProducts = ProductDataLayer.GetProducts(this.CurrentCustomer));
      }
   }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读