Sunday, 19 May 2019

Be careful with MemoryCache

Imagine a .NET code block like below:


var memCache = new System.Runtime.Caching.MemoryCache("Cache1");
            memCache.Add("Key1", "Val1", new CacheItemPolicy() { AbsoluteExpiration = DateTime.UtcNow.AddDays(1) });
            Console.WriteLine(memCache["Key1"]);
            var memCache2 = new System.Runtime.Caching.MemoryCache("Cache1");
            Console.WriteLine(memCache2["Key1"]);
            Console.WriteLine(memCache["Key1"]);

What do you expect in output?

Well, as opposed to what some might expect, 2 line printed on console is null.

In fact, if you extend the code to like below, you will come to realize that everytime you new up a MemoryCache instance; even if it is with same name within same process, it is a different one.

var memCache = new System.Runtime.Caching.MemoryCache("Cache1");

            memCache.Add("Key1", "Val1", new CacheItemPolicy() { AbsoluteExpiration = DateTime.UtcNow.AddDays(1) });
            Console.WriteLine(memCache["Key1"]);
            var memCache2 = new System.Runtime.Caching.MemoryCache("Cache1");
            Console.WriteLine(memCache2["Key1"]);
            Console.WriteLine(memCache["Key1"]);
            memCache2.Add("Key1", "Val2", new CacheItemPolicy() { AbsoluteExpiration = DateTime.UtcNow.AddDays(1) });
            Console.WriteLine(memCache2["Key1"]);
            Console.WriteLine(memCache["Key1"]);
            Console.ReadLine();


Keep this in mind and save yourself from some weird performance issues :).

No comments:

Post a Comment