lukas
lukas

Reputation: 106

Cache data outside of Application

Im trying to cache data that i get from a SQL Service, i tried using the Memory Cache Class from System.Runtime.Caching but it seems like the Cache is being emptied whenever i exit the Application.

So my Question is, is there a way to Cache my Data so i can get it even if my Application restarted?

Im Working with a Service from Biztalk so the Application gets started whenever its needed, but the SQL polling takes too long.

Here is the Code im testing with:

const string KEY = "key";

    static void Main(string[] args)
    {
        MemoryCache cache = MemoryCache.Default;

        Cache(cache);
        Get(cache);
        Console.Read();
    }

    private static void Get(MemoryCache cache)
    {
        string result = cache.Get(KEY) as string;
        Console.WriteLine(result);
    }

    private static void Cache(MemoryCache cache)
    {
        CacheItemPolicy policy = new CacheItemPolicy();
        policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10);
        bool res = cache.Add(KEY, "This was Cached", policy);
        if (res)
            Console.WriteLine("Added Succesfully");
        else
            Console.WriteLine("Adding Failed");
    }

Upvotes: 4

Views: 1838

Answers (1)

NightOwl888
NightOwl888

Reputation: 56859

So my Question is, is there a way to Cache my Data so i can get it even if my Application restarted?

Yes. If you use CacheItemPriority.NotRemovable, the cache will survive even if the application restarts.

ObjectCache cache = System.Runtime.Caching.MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy
{
    Priority = CacheItemPriority.NotRemovable,
    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10);
};

cache.Add(item, policy);

MSDN NOTE: Adding an entry to the cache with a priority level of NotRemovable has the potential to overflow the cache with entries that can never be removed. Cache implementations should only set the NotRemovable priority for a cache entry if they provide ways to evict such entries from the cache and to manage the number of cache entries.

Upvotes: 2

Related Questions