ASP.NET – Use Context.Cache to cache data for http request

The best way to speed up ASP.NET application is to use cache for speeding up the velocity of reading/writing data. Every developer knows that reading/writing memory is orders of magnitude faster than reading/writing files or database on hard disk. Hence reading/writing files or databases for each HTTP request is not a wisdom way. In this small post, I would like to illustrate how man can use ASP.NET for his application.

The ASP.NET application cache is a smart in-memory repository for data. It’s smart because it allows items entrusted to it to be assigned expiration policies, and also because it fires notifications when it removes items from the cache, affording applications the opportunity to refresh the cache by replacing old data with new. It’s also flexible. It’s capable of caching instances of any type that derives from System.Object, from simple integers to complex types that you define yourself.
This example will read all lines in a text file and split it into many single lines then store them in a List. A label will read this List and fetch randomly one line and show it to the users. Instead of reading this text file each time when user accesses this page, I will store this list in Context.Cache and take data from this cache.

protected void Page_Load(object sender, EventArgs e)
{
	if (Context.Cache["DataSource"] == null)
	{
		Application_Start(sender, e);
		LoadInformation();
	}
	else
	{
		LoadInformation();
	}
}

In the Page_Load function, I examine if the Cache with key “DataSource” is already available. If not, I will create a Cache object “DataSource”.

protected void Application_Start(object sender, EventArgs e)
{
	m_strPath = Server.MapPath("DataSource.txt");            
	RegisterCache();
}

private void RegisterCache()
{
	List<string> lstItems = ReadDataSource();
	Context.Cache.Insert("DataSource", lstItems, new CacheDependency(m_strPath),
		System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration,
		CacheItemPriority.Default, new CacheItemRemovedCallback(RefreshDataSource));
}

The ASP.NET application cache’s most important feature is its support for cache removal callbacks which I used above, to be notified when an item is removed. I pass a CacheItemRemovedCallback delegate to Insert function identifying the method to be called when ASP.NET removes the item from the cache. For more details about Insert function you can read at http://msdn.microsoft.com/en-us/library/system.web.caching.cache.insert.aspx .
The callback function just reads the data source again and register the cache object

private void RefreshDataSource(String key, Object item, CacheItemRemovedReason reason)
{            
	RegisterCache();
}

Because high volume Web servers are often required to process hundreds (or thousands) of requests per second, every millisecond counts when designing for performance. The ASP.NET application cache is a fine tool for maximizing performance by minimizing time-consuming file and database I/O. Use it early and use it often.The complete source code of this example you can download here “ASP.NET Context.Cache“.

Leave a Reply

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