Simple C# ASP.NET Cache Implementation

前端 未结 3 1547
面向向阳花
面向向阳花 2020-12-17 01:29

I need to build up a List and cache the list and be able to append to it. I also need to be able to blow it away easily and recreate it. What is
3条回答
  •  渐次进展
    2020-12-17 02:11

    Something like this perhaps?

    using System;
    using System.Collections.Generic;
    using System.Web;
    
    public class MyListCache
    {
        private List _MyList = null;
        public List MyList {
            get {
                if (_MyList == null) {
                    _MyList = (HttpContext.Current.Cache["MyList"] as List);
                    if (_MyList == null) {
                        _MyList = new List();
                        HttpContext.Current.Cache.Insert("MyList", _MyList);
                    }
                }
                return _MyList;
            }
            set {
                HttpContext.Current.Cache.Insert("MyList", _MyList);
            }
        }
    
        public void ClearList() {
            HttpContext.Current.Cache.Remove("MyList");
        }
    }
    
    
    

    As for how to use.....

    // Get an instance
    var listCache = new MyListCache();
    
    // Add something
    listCache.MyList.Add(someObject);
    
    // Enumerate
    foreach(var o in listCache.MyList) {
      Console.WriteLine(o.ToString());
    }  
    
    // Blow it away
    listCache.ClearList();
    

    提交回复
    热议问题