Simple C# ASP.NET Cache Implementation

2019-01-24 14:33发布

I need to build up a List<object> 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 a simple way to accomplish this?

3条回答
趁早两清
2楼-- · 2019-01-24 14:47

This Tutorial is what I found to be helpful

Here is a sample

List<object> list = new List<Object>();

Cache["ObjectList"] = list;                 // add
list = ( List<object>) Cache["ObjectList"]; // retrieve
Cache.Remove("ObjectList");                 // remove
查看更多
叼着烟拽天下
3楼-- · 2019-01-24 15:03

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();
查看更多
相关推荐>>
4楼-- · 2019-01-24 15: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:

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

查看更多
登录 后发表回答