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

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

Using Cache:

If Cache("myDataSet") Is Nothing Then
	MyDataSet()
	'DataSet from database
Else
	ds = CType(Cache("myDataSet"), DataSet)
	' DataSet from cache.
End If

Clear Cache:

  Cache.Remove("myDataSet")

Clear ALL Cache vars:

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

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

HttpRuntime.Close()

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *