SolutionCottage.com
Posted  19 Mar 2009 - 23:18:45

Category: ASP.net


Using cache in an ASP.net website.

Issue:
You want to implement caching on your website.

Solution:
This simple example will explain how the Cache object works in ASP.net. Basically I have a simple page with two controls, a button (btnUpdate) and a label (lblOutput).

When you press the button, the function will check if there is a value with the cachekey we have choosen. If there is no object, we need to create one by setting the current DateTime to the object and then insert it into the cache for future calls. If there is a cached object we just put that into the object and show it in the label.

Here is the example code:

protected void btnUpdate_Click(object sender, EventArgs e)
{
string cacheKey = "Mikael";
string outPut = null;

if (Cache[cacheKey] == null)
{
outPut = DateTime.Now.ToString();
Cache.Add(cacheKey, outPut, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.TimeSpan.FromSeconds(10), CacheItemPriority.Default, null);
}
else
{
outPut = (string)Cache[cacheKey];
}

lblOutput.Text = outPut;

}



Marked as helpful by 1 user




0 comments:








© SolutionCottage 2008-2011 7/21/2017 3:36:36 AM