Cache data

In this post, we’ll examine two ways of how to cache data in a .NET Framework application. For ASP.NET web apps, we’ll use SqlCacheDependency, and for desktop applications, we’ll consider using the Local Data Cache.

When dealing with ASP.NET applications, you have multiple choices to cache data, by using one of the state management techniques (I have written multiple posts about them, so search for them), but for now, we’ll consider using the Cache class. Before you’d write any data caching code, you should start in the web.config, as usual. Take a look at the following block:

<sqlCacheDependency pollTime=”1000” enabled=”true”>
<add connectionStringName=”aString” name=”databasename”/>

After this, you should place something similar to your data access class:

SqlCacheDependency scd = null;
while(sdc == null)
sdc = new SqlCacheDependency(“databaseName”, “tableName”);
SqlCacheDependencyAdmin.EnableTableNotifications(connectionString, “tableName”);
Cache.Insert(“name”, object, sdc);

You should try instantiating your SqlCacheDependency classes inside a using block, because there might be exceptions occurring because of improperly set databases. To resolve these issues, you can use the SqlCacheDependencyAdmin class. This class exposes static methods to turn database and table notifications on/off. Setting these is required to the dependency object to work properly.

Another method to cache data is Local Data Cache, you’d use it in your desktop applications. It is very easy to implement them,  you can hold the data in memory on your desktop computer, or store it in a file. I think you are able to retrieve and store data in both ways, so just try and experiment with it.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s