Articles in categories

Articles

Simple caching in C#

I've done my first simple caching in C# with dotnet 4. In my application I load 500+ product objects and place them in a List<T>. Later I wanted to be able to allow filtering on the retrieved list so I needed to store the original list somewhere.

Then I found caching :) Ofcourse, I've heard from it before , but never used it myself.

I need to do a lot of more searching, reading and experimenting with caching if I want to know more about how to use it. Not even sure how I use it now is entirely correct but it works for me, for now.

Here is a very simple implementation:

using System.Runtime.Caching;

private readonly ObjectCache _cache = MemoryCache.Default;

public void GetAllProducts()
{
  // Set the _cache["products"] with a list of Products
  _cache["products"] = ProductRules.GetAllProducts().OrderByDescending(p => p.Code).ToList();
	
  // Retrieve Products from the cache
  if (_cache["products"] != null)
    List<Product> products = (List<Product>)_cache["products"];
}

More info about caching: