6

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?

1
  • 1
    Keep in mind your List will not be thread safe. Commented Mar 16, 2010 at 21:51

3 Answers 3

18

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();
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Yes Bryan, this example is quite simple. - But I took your suggestion to heart and updated my sample. Thanks.
In many/most real world scenarios you'll want to flush changes to some kind of persistant storage.
2

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

link is broken :(
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.