How to use Memcached in ASP.Net applications

Download Sample Project (218.91 kb)

Caching data, pre-rendered pages, responses etc. are all part of good architecture for a high performance ASP.Net application. Actually for that matter same holds true for any application. If you can save time on fetching data from database or pre-render some presentation then any time of application will benefit from cache. In this post I am just going to concentrate on caching in ASP.Net application. And mainly how to use Memcached as state server for caching in your application.

What is Memcached?

I am not going to go into discussion about Memcached here. There is lot of very good information available on this opensource application's site itself. You can click here to read everything about it. In nutshell Memcached is a open source, high-performance, distributed memory object caching system.

What to use Memcached?

Now big question you are asking is why should you use Memcached? What is wrong with state server provided by ASP.Net state server? Simple answer, there is no problem with ASP.Net state server. There is one term that distinguishes ASP.Net state server and custom caching server is term DISTRIBUTED. Solutions like Memcached provide distributed and clustered state server. Having a distributed state server ensures near 100% uptime and reliable ASP.Net web application in web farm or web garden configuration.

List of distributed caching software

Before you start using Memcached, let me provide you list of alternatives that can be used for state server. This is not all the list, just some of the ones that I have run into and used from time to time.

How to use Memcached?

There are just few simple steps you need to perform to get started with using Memcached.

Install Memcached

First you will need to install Memcached service on your machine. I am going to keep this in perspective of Windows OS. There are now installers available that will install Memcached on your server with click of a button. The ones that I have used very extensively at few places is from Couchbase. Download the community edition to try. I will not discuss installation and configuration of Memcached in this post. That will be part of discussion for another post. But if you have questions please feel free to drop me a line. Just follow the instructions after installation wizard launches the admin console.

Get .Net API to connect to Memcached service

Memcached is a windows service installed on your machine and communicates through sockets. So you will need a client API that can communicate with this service. There are few opensource APIs available. The one that I use is a port of a JAVA api. You can click here to download it from sourceforge. The code is little old but works like a charm. You can get the source and compile it for .Net4.0 if you want to or compile it for .Net 2.0 depending on framework(s) you want to target. And then add a reference to this library in your project.

Use it in ASP.Net

Now that you have client library to connect to Memcached, only thing left is to get your ASP.Net application to start using it. For introduction I will just discuss how you can instantiate an instance of client library and then store some objects and then get them from cache. In later post I will discuss building a .Net cache provider around Memcached so caching is transparent to your .Net application.

Here is code snippet that I used to initialize use of cache service in my application. This code has been directly taken from code sample that comes with client library code.

public void Initialize()
      Initialized = false;
      // initialize the pool for memcache servers
      _pool = SockIOPool.GetInstance();
      Servers = new string[] { "" };
      _pool.InitConnections = 3;
      _pool.MinConnections = 3;
      _pool.MaxConnections = 5;

      _pool.SocketConnectTimeout = 1000;
      _pool.SocketTimeout = 3000;

      _pool.MaintenanceSleep = 30;
      _pool.Failover = true;

      _pool.Nagle = false;

      // get client instance
      _clientInstance = new MemcachedClient();
      _clientInstance.EnableCompression = false;

     Initialized = true;
  catch (Exception ex)
     Initialized = false;
     throw new ApplicationException("Failed to initialize memcached provider", ex);

As you can see from the code that service provides lot of configuration parameters to control behaviour of caching as per your application requirements. At the very basic level you just need to methods that will save object in cache then get it.

public void Set(string key, object data, DateTime expireAt)
   _clientInstance.Set(key, data, expireAt);
public object Get(string key)
  return _clientInstance.Get(key);

And then using the API in your application is as simple as following code.

ApplicationCache.CacheStorage.Set("SelectedOptions", _selectedOptions);
//Session["SelectedOptions"] = _selectedOptions;
_selectedOptions = ApplicationCache.CacheStorage.Get("SelectedOptions") as List<int>;

As you can see how easy it is to get started with a robust distributed caching service for your ASP.Net application. In subsequent posts I will discuss more features of use of Memcached service.




0.1 °C / 32.1 °F

weather conditions Clouds

Monthly Posts

Blog Tags