Using the data cache in the simplest and most naive way supported by ASP.NET is very much like accessing the Session object. Remember, accessing the Session
object involves using an indexer (the square bracket syntax) and a
consistent index to store and retrieve data. The data cache works in
exactly the same way (although it has some other features for managing
items in the cache).
The strategy for caching a piece of data usually involves these steps:
Look in the cache for the data element.
If it's there, use it (bypassing the expensive database round-trip).
If the data element is unavailable in the cache, make a round-trip to the database to fetch it.
If you had to fetch the data, cache the data element so that it is available next time around.
The next example modifies
the UseDataList page so that it stores the data item in the cache after
acquiring it for the first time. Although the first time Page_Load is called it might take a while (on a computer's time scale), subsequent calls are much faster.
Using the cache
Open the UseDataList.aspx.cs file and go to the GetInventory method.
Modifying
the method to use the cache is fairly straightforward. The following
listing highlights the changes. First, check to see whether the item is
in the cache. If searching the cache for the DataSet turns up a valid object reference, you can bypass the database lookup code and return the referenced DataSet.
If searching the cache turns up a null object reference, go ahead and
make the round-trip to the database. When the database lookup finishes,
you'll have a good DataSet (provided the query succeeds). Cache it before returning the reference to the caller. If you include the Trace statements, you can see exactly how big an impact caching can make. The changes you need to make are shown in bold type:
protected DataTable GetInventory()
{
DataTable dt = null;
Trace.Warn("Page_Load", "looking in cache");
dt = (DataTable)Cache["InventoryDataTable"];
Trace.Warn("Page_Load", "done looking in cache");
if (dt == null)
{
Trace.Warn("Page_Load", "Performing DB lookup");
dt = new DataTable();
string strConnection =
@"Data Source=
.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|ASPNETStepByStep4.mdf;
Integrated Security=True;
User Instance=True";
DbProviderFactory f =
DbProviderFactories.GetFactory("System.Data.SqlClient");
using (DbConnection connection = f.CreateConnection())
{
connection.ConnectionString = strConnection;
connection.Open();
DbCommand command = f.CreateCommand();
command.CommandText = "Select * from DotNetReferences";
command.Connection = connection;
IDataReader reader = command.ExecuteReader();
dt.Load(reader);
reader.Close();
connection.Close();
}
Cache["InventoryDataTable"] = dt;
Trace.Warn("Page_Load", "Done performing DB lookup");
}
return dt;
}