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?
-
1Keep in mind your List will not be thread safe.dugas– dugas2010-03-16 21:51:28 +00:00Commented Mar 16, 2010 at 21:51
Add a comment
|
3 Answers
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();
3 Comments
Bryan
Well... serviceable. But I would make some changes. Primarily, I would always return a valid list. If it doesn't exist, create a new empty collection and cache it, rather than just returning whatever is in Cache["MyList"], which might be null.
jessegavin
Yes Bryan, this example is quite simple. - But I took your suggestion to heart and updated my sample. Thanks.
quillbreaker
In many/most real world scenarios you'll want to flush changes to some kind of persistant storage.
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
1 Comment
Daniel Barnes
link is broken :(
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.