We add three buttons on the page and create event handling methods for double-clicking the buttons. The three buttons add ASP.NET cache using different expiration strategies.
<asp:Button ID="btn_InsertNoExpirationCache" runat="server" Text="Insert never-expiration cache"
OnClick="btn_InsertNoExpirationCache_Click" />
<asp:Button ID="btn_InsertAbsoluteExpirationCache" runat="server" Text="Insert absolute time
Expiration cache" OnClick="btn_InsertAbsoluteExpirationCache_Click" />
<asp:Button ID="btn_InsertSlidingExpirationCache" runat="server" Text="Insert change time
Expiration cache" OnClick="btn_InsertSlidingExpirationCache_Click" />
The Click event handling methods of the three buttons are as follows:
protected void btn_InsertNoExpirationCache_Click(object sender, EventArgs e)
{
DataSet ds = GetData();
Cache.Insert("Data", ds);
}
protected void btn_InsertAbsoluteExpirationCache_Click(object sender, EventArgs e)
{
DataSet ds = GetData();
Cache.Insert("Data", ds,null, DateTime.Now.AddSeconds(10), TimeSpan.Zero);
}
protected void btn_InsertSlidingExpirationCache_Click(object sender, EventArgs e)
{
DataSet ds = GetData();
Cache.Insert("Data", ds, null, DateTime.MaxValue, TimeSpan.FromSeconds(10));
}
Let’s analyze these three ASP.NET cache expiration strategies.
◆Never expires. Just assign the cached Key and Value directly.
◆Absolute time expiration. DateTime.Now.AddSeconds(10) means that the cache will expire after 10 seconds, and TimeSpan.Zero means that the smooth expiration strategy is not used.
◆Expiration of changing time (smooth expiration). DateTime.MaxValue means that the absolute time expiration policy is not used, and TimeSpan.FromSeconds(10) means that the cache will expire without access for 10 consecutive seconds.
Here, we have used the Insert() method to add cache. In fact, Cache also has an Add() method that can also add items to the cache. The difference is that the Add() method can only add items that are not in the cache. If you add an item that is already in the cache, it will fail (but no exception will be thrown), while the Insert() method can overwrite the original item.
Note: Unlike Application, there is no need to use lock operations when inserting into the ASP.NET cache. Cache will handle concurrency by itself.