cache in csharp

cache in csharp

This is a wrapper around HttpRuntime.Cache i use when some object is to expensive to get from its source every time. For example a RSS-feed which might only need to get updates from its source every minute.

using System;
using System.Web;
using System.Web.Caching;

public class HttpRuntimeCache
{
    private DateTime _Expiration;

    public DateTime Expiration
    {
        get
        {
            return this._Expiration;
        }
        set
        {
            this._Expiration = value;
        }
    }

    public HttpRuntimeCache()
    {
        this._Expiration = DateTime.Now.AddHours(4);
    }

    public void Add(string key, object objectToCache)
    {
        this.ValidateKey(key);
        this.ValidateCacheObject(objectToCache);
        HttpRuntime.Cache.Add(key, objectToCache, null, this._Expiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
    }

    public object Get(string key)
    {
        this.ValidateKey(key);
        return HttpRuntime.Cache.Get(key);
    }

    public void Remove(string key)
    {
        this.ValidateKey(key);
        HttpRuntime.Cache.Remove(key);
    }

    private void ValidateKey(string key)
    {
        if (key == null)
        {
            this.ThrowNullKeyError();
        }
        if (key.Length == 0)
        {
            this.ThrowEmptyKeyError();
        }
    }

    private void ValidateCacheObject(object objectToCache)
    {
        if (objectToCache == null)
        {
            this.ThrowObjectError();
        }
    }

    private void ThrowObjectError()
    {
        throw new ArgumentNullException("objectToCache");
    }

    private void ThrowNullKeyError()
    {
        throw new ArgumentNullException("key");
    }

    private void ThrowEmptyKeyError()
    {
        throw new ArgumentException("Input cannot be empty", "key");
    }
}

This code shows how to add and remove a string from the cache. If it’s not removed it will stay there for 4 hours which is set in the contstructor of HttpRuntimeCache class.

string simpleString = "this string will be cached";
HttpRuntimeCache cache = new HttpRuntimeCache();
cache.Add("simpleString", simpleString);
string fromCache = cache.Get("simpleString") as string;
cache.Remove("simpleString");

Change cache expiration

To change the expiration the Expiration property can be set before adding the object to the cache:

string simpleString = "this string will be cached";
HttpRuntimeCache cache = new HttpRuntimeCache();
cache.Expiration = DateTime.Now.AddHours(1);
cache.Add("simpleString", simpleString);