ALLINSIGHT

Home of the AlmostImplementedException

Caching objects in .Net with MemoryCache

In .Net 4.0 Microsoft indroduces a new universal cache. For quite some time caches were already present in ASP.Net, but could (should) not be used in C# or VB.Net. With the new package System.Runtime.Caching there is now an easy way to implement a cache in any program, like a WebService or WPF-Application. As you will see, the caching package can manage all the object you want to cache, including different timeouts and proper memory usage.

To test the cache, create a new Project (WPF, Console, WCF or what ever you want) and include the System.Runtime.Caching.dll. Create a new class, add the using System.Runtime.Caching and a method called GetObject(int id). This method simulates a long taking request, maybe to a database and it will cache the object.

Here is a simple example how to add an object to the cache for 10 seconds.

First we need to get the default MemoryCache, because we want the objects in memory. After that we create a new policy to set a timeout. Without that the object will be cached forever. And finaly we add the object to the cache with Add, AddOrGetExisting or Set. For that we have to give the object a name. A good way to generate a name is to use the objecttype as prefix and the id.
The Add-method has a bool as return value indicating the sucessful addition of an object to the cache. If the object already exists the return value is false and the old value is in the cache. When you use Set always the new value is cached (overwriting the old value).
Sometimes you want to use the Cache in a Multi-Threaded environment. Maybe you want to cache a random number for 60 minutes as calculation base for all processes, but if the number expires the first thread needing it generates a new one. With Get you may not get a value if someone else is writing it at the same time and if you later call Add or Set, you’ll overwrite the value. Even so the MemoryCahe is thread safe, between the get and set call someone else may set a value.
AddOrGetExisting is the solution, if there is no value you use the new object and add it to the cache. If someone else is doing the same thing, he’ll get the cached object instead of his own.

To get a value from the cache, you simply call Get with the name you gave the object. If the value isn’t expired you will get it from the cache.

Here is a final simple example how i used the cache in a webservice (WCF-SOAP) to cache DB-Calls.

To create your own cache (only your program can use it) you simply create a new MemoryCache-Instance with new MemoryCache(“myCache”); This way you can use multiple caches and dispose and recreate them as needed.

To clear a cache of all wanted objects without recreation (maybe you want only to clear your Text-Cache) you have to use the following code the cache-developers provides:

http://connect.microsoft.com/VisualStudio/feedback/details/723620/memorycache-class-needs-a-clear-method

Conclusion
It is very easy to use the .Net cache in your own programs. The cache uses expiration dates and take care of the memory usage. You can set different expiration times to cache long life objects like article texts and short-life (fast changing objects) like prices or availability. You can us one cache for all or separate caches for each object-types (easier to handle for manual resets)

Share :

, ,

4 thoughts on “Caching objects in .Net with MemoryCache

Leave a Reply

Your email address will not be published. Required fields are marked *