Saturday 5 July 2014

Asp.Net caching

For total performance, ASP.NET includes a very powerful and easy to use caching system. Any object can be sent to the cache for later retrieval, with total control on its life span. For example, the code below fetches results from a database (see the section on Data Access later for more information):
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter a = new SqlDataAdapter("select * from mytable;", conn);
DataSet s = new DataSet();
a.Fill(s);
We can cache the results (in this case, represented by a DataSet) of our query, so subsequent requests will not need to connect to the database to complete the request. How easy is ASP.NET caching? Take a look:
Cache["databasequery"] = s;
Once an object is stored within the cache, we can access it again in a similarly easy way:
s = (DataSet)Cache["databasequery"];
Before we access the cache however, it is important we first check there is something available in the cache. So, introducing caching to our earlier code means only 3 extra lines of code:
DataSet s = new DataSet();
if (Cache["databasequery"] == null) {
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter a = new SqlDataAdapter("select * from mytable;", conn);
a.Fill(s);
Cache["databasequery"] = s;
}
else
{
s = (DataSet)Cache["databasequery"];
}
ASP.NET can also cache complete pages. By adding a directive to the page, caching can be controlled by a parameter (e.g. http://mydomain.com/myresource.aspx?clearcache=true) or by the IP address of the requestor, and a timeout for the cache can be set.