Coding Tips & Tricks


Home > Cache

Memcached for C# - A Walkthrough

A while ago I wrote about Object caching in .NET 4. I think that the Object Caching in .NET 4 is a great tool to use for caching and literally takes minutes to get up and running. However, one of the downsides of using the System.Runtime.Caching in .NET 4 is that every time your application pool recycles in IIS, you lose the objects in cache. The same happens if you make a change to your web.config or redeploy your application.

This isn't a problem if you are running smaller applications and cached data isn't vital to their performance. However, for high-traffic applications that need to have the cache up all the time, this becomes a problem. Another thing to consider is the possibility of load-balanced servers - using the Object Caching in .NET 4 isn't distributed. That means it will only store its cache per application pool. If you have two servers it means that you will have two different cache stores.

Memcached Logo

I have recently been introduced to the world of Memcached. Memcached is a free & open source, high-performance, distributed memory object caching system intended for use in speeding up dynamic web applications by alleviating database load. You can think of it as a short-term memory for your applications. The brilliant thing about Memcached is that you run it on one server and point all the applications to the Memcached server. This way all servers use the same cache! Another bonus is that even if you redeploy your app, or recycle the app pool in any way - the cached objects are still there. This is great news for larger applications that need to be online constantly and can't afford any downtime with regards to it's cache.

Memcache server usage

Memcached is no new comer to the web. It is used by major players such as Wikipedia, Flickr, Twitter, Youtube, WordPress.com and Digg. The advantages of using Memcached are endless and getting it setup on your machine is really simple. There are two parts to getting Memcached setup - you need the Memcached server and then you need to get the client API. There are few client API available for most of the common languages out there (Ruby, C#, PHP, C, Java).

I had a bit of trouble actually finding a decent ready-to-go implementation of Memcached for Windows. I got my version 1.4 from this site, but it seems that there are also other versions available here and here. Once you have downloaded the files, you can either run Memcached as a console application or install it as a Windows service (This is the recommended option). In order to install it as a service, run the following from the command line:

C:\yourmemcachedpath\memcached -d install

Next, you need to get the client API to start using the cache. There are a few different options with regards to the C# client API, but I chose Enyim Memcached. Open Visual Studio, create a new project and add a reference to the Enyim.Caching library that you downloaded.

Add Reference

You will also need to update your web.config or app.config to include the following lines. In your configSections:

Enyim Memcached Config

And then just before the end of the web.config file add the following:

Enyim Memcached Config

You will notice that the address is "127.0.0.1" and port "11211". This would normally be the network location that your Memcached server is hosted on, but in this instance I am testing it locally and this is the default.

Using the library is really simple and intuitive. Although it's not a real world example, the following code will store and retrieve a value from the cache.

Enyim Memcached Code

A while ago I wrote about Object caching in .NET 4. I created a little wrapper that used simple syntax and wrapped around the System.Runtime.Caching namespace. Using the same class, we can just update it to point to our Memcached server. If it makes it easier for you to use the class I wrote and combined with the Memcached API, it is available for download here. Also, just in case the Memcached servers are not available at any of the locations I defined above - you can download version 1.4 here.

I searched the web and found that there is very little documentation with regards to C# out there - I hope this article helped to get you up to speed with Memcached!








Comments

Darren - 9/27/2011
Dean I had a look at this last year for C# and at the time was disappointed with the lack of knowledge and support within the community. This is a useful post and a step in the right direction. Memcached is a very good tool - one that ASP.Net developers would benefit from using more. Thanks

Dean Hume - 9/29/2011
Hi Darren Thanks for the comment! Yeah, I had the same problem when I was researching Memcache. Hope it helped - Dean

friism - 10/6/2011
If you don't want to mess around with setting up memcached on Windows, you can run you app on AppHarbor (https://appharbor.com/). We also maintain an updated memcached sessionstateprovider, there's a guide on how to use it here: http://support.appharbor.com/kb/tips-and-tricks/using-memcached-backed

Gabriel Rodriguez - 10/6/2011
I was recently considering playing with memcached and .NET but just like you said, there wasn't a lot of material around. Gonna probably try it tonight thanks to your article. Thanks Dean.

Shaun Danielz - 10/7/2011
Perhaps your article should cover AppFabric caching services?

Tony - 12/9/2011
How to avoid using Web.config and app.config?

Andrei Rinea - 12/14/2011
I'm really curios about the performance of getting/setting items from/into the memcached instance. Any data?

Boris - 2/17/2012
when i try to install memcached 1.4 as service (-d install) i get such error: Failed to ignore SIGHUP: Result too large failed to daemon() in order to daemonize but if i run it as executable it works fine. how to fix it?

Rahul - 2/23/2012
Hi, I've been reading about Memcached and it's significant use in many famous sites. I've this doubt that is it possible to build applications like facebook or foursquare completely in .Net technologies (using My SQL as backend)?

Rahul - 2/23/2012
My question has more to do with performance and latency? I don't hear anybody opting for .Net technologies for their now famous products. Or is it just a issue about license/product fee associated .Net platform? I'm sorry as It may be not be the right place to ask this but I'm just very curious.

Vishal - 3/29/2012
Great article. Just couple of additions - You need to run as administrator to install the service and for complex objects remember to add [Serializable] before your class.

Ratul Saikia - 10/10/2013
Its easier to get the client directly from Nuget(Visual Studio manage Nuget Packages) rather then getting the C# project from git, built it and then add the reference.

MaxMa - 9/5/2014
Sample code to avoid using web.config and app.config. MemcachedClientConfiguration config = new MemcachedClientConfiguration(); config.AddServer("127.0.0.1", 11211); config.Protocol = MemcachedProtocol.Text; MemcachedClient memcahce = new MemcachedClient(config);

MaxMa - 9/5/2014
download Enyim.Caching dll https://github.com/enyim/EnyimMemcached/downloads

Zazzles - 9/30/2014
Great article! I would like to use Memcached, but it isn't distributed. If I'm wrong, could your please explain how I can share Memcached data between instances.

Peter - 11/18/2014
Check about repcached, Zazzles


Add your comment

300 Characters left


Please fill this in to confirm that you are human