Monday, January 21, 2013

A Simple Cache Example in ASP.NET


The following page presents a simple caching test. An item is cached for 30 seconds and reused for requests in that time. The page code always runs (because the page itself isn’t cached), checks the cache, and retrieves or constructs the item as needed. It also reports whether the item was found in the cache.

public partial class SimpleDataCache : System.Web.UI.Page
{
protected void Page_Load(Object sender, EventArgs e)
{
if (this.IsPostBack)
{
lblInfo.Text += "Page posted back.<br />";
}
else
{
lblInfo.Text += "Page created.<br />";
}
if (Cache["TestItem"] == null)
{
lblInfo.Text += "Creating TestItem...<br />";
DateTime testItem = DateTime.Now;
lblInfo.Text += "Storing TestItem in cache ";
lblInfo.Text += "for 30 seconds.<br />";
Cache.Insert("TestItem", testItem, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
}
else
{
lblInfo.Text += "Retrieving TestItem...<br />";
DateTime testItem = (DateTime)Cache["TestItem"];
lblInfo.Text += "TestItem is '" + testItem.ToString();
lblInfo.Text += "'<br />";
}
lblInfo.Text += "<br />";
}
}

Figure shows the result after the page has been loaded and posted back several times in the 30-second period.




1 comment:
Write comments
Recommended Posts × +