Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache data outside of Application

Tags:

c#

.net

caching

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");
    }
like image 808
lukas Avatar asked Oct 15 '25 04:10

lukas


1 Answers

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.

like image 161
NightOwl888 Avatar answered Oct 17 '25 17:10

NightOwl888



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!