Using “Cache” in ASP.Net

 Data can be stored on the client – using the view state of the page, or on the server in a variable session state or application, or using the server cache.
ASP.NET implements System.Web.Caching.Cache class to store objects that require a large amount of server resources to be created, so that they do not have to be recreated each time it is needed.
You can access via code information about a class instance cache through the property cache, the object of the HttpContext or Page object.
Expiration policy for items in cache:
  • Specific time:  absolute expiration
  • May also expire if not accessed for a period of time:  sliding expiration

Insert Into cache

[vb]
Cache.Insert("myDataSet", ds, Nothing, DateTime.Now.AddSeconds(30), System.TimeSpan.Zero)
[/vb]

Using Cache:

[vb]
If Cache("myDataSet") Is Nothing Then
MyDataSet()
‘DataSet from database
Else
ds = CType(Cache("myDataSet"), DataSet)
‘ DataSet from cache.
End If
[/vb]

Clear Cache:

[vb]
Cache.Remove("myDataSet")
[/vb]

Clear ALL Cache vars:

[vb]
Dim enumerator As IDictionaryEnumerator = HttpContext.Current.Cache.GetEnumerator()
While enumerator.MoveNext()
HttpContext.Current.Cache.Remove(enumerator.Key)
End While
[/vb]

Note that, this technique is not efficient for pages with OutputCache type. for clearing this type cached memory, you should use below code line.

[vb]
HttpRuntime.Close()
[/vb]

Comments are closed.