.NET classes you might not know about: MemoryCache

Posted: (EET/GMT+2)

 

The MemoryCache class in the System.Runtime.Caching namespace gives you a simple in-process cache with expiration and cache eviction. It is useful when you want to keep expensive results around for a while without introducing a full distributed cache.

Here is a basic example on how to use MemoryCache:

using System;
using System.Runtime.Caching;

public static class CacheDemo
{
    private static readonly MemoryCache _cache = MemoryCache.Default;

    public static string GetData()
    {
        string key = "my-data";
        if (_cache.Contains(key))
        {
            return (string)_cache[key];
        }

        string value = "Computed at " + DateTime.UtcNow;
        var policy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(5)
        };
        _cache.Set(key, value, policy);
        return value;
    }
}

You can configure size limits, sliding expirations, and change monitors (for example, invalidate when a file changes). For web applications, ASP.NET has its own cache APIs, but for console applications, Windows background services, or libraries, the MemoryCache class is a handy built-in option.