Simple C# ASP.NET Cache Implementation

前端 未结 3 1501
面向向阳花
面向向阳花 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:03

    This Tutorial is what I found to be helpful

    • ASP.NET Caching Features

    Here is a sample

    List<object> list = new List<Object>();
    
    Cache["ObjectList"] = list;                 // add
    list = ( List<object>) Cache["ObjectList"]; // retrieve
    Cache.Remove("ObjectList");                 // remove
    
    0 讨论(0)
  • 2020-12-17 02:07

    The caching parts of "Tracing and Caching Provider Wrappers for Entity Framework", while not simple, are still a pretty good review of some useful things to think about with caching.

    Specifically, the two classes InMemoryCache and AspNetCache and their associated tests:

    • ICache
    • InMemoryCache and tests
    • AspNetCache

    Similar to what the question did, you could wrap HttpRuntime.Cache or HttpContext.Current.Items or HttpContext.Current.Cache in an implementation of ICache.

    0 讨论(0)
  • 2020-12-17 02:11

    Something like this perhaps?

    using System;
    using System.Collections.Generic;
    using System.Web;
    
    public class MyListCache
    {
        private List<object> _MyList = null;
        public List<object> MyList {
            get {
                if (_MyList == null) {
                    _MyList = (HttpContext.Current.Cache["MyList"] as List<object>);
                    if (_MyList == null) {
                        _MyList = new List<object>();
                        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();
    
    0 讨论(0)
提交回复
热议问题