Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

ASP.NET: Data Caching

From Wiki

Jump to: navigation, search

Summary: An example of how you can cache data within your application

ASP.NET provides an OutputCache method that allows you to cache a page on the server so that future requests don't have to recreate the page. However, there may be times when you want to cache something programmatically so that you can use that object across multiple page. Luckily, this is very easy to do and here's a simple example that shows how to cache a DataTable for 1 hour:

  1. Public Function GetData() As DataTable
  2.  
  3.     ' Create a new DataTable and set it to the cached version  
  4.     Dim dt As New DataTable
  5.     dt = HttpContext.Current.Cache.Get("MyData")
  6.  
  7.     ' Check if the DataTable exists in the cache  
  8.     If dt Is Nothing Then
  9.         ' Place your code to get your data here  
  10.         MyDataTable = ...  
  11.  
  12.         ' Add the DataTable to the cache  
  13.         HttpContext.Current.Cache.Insert("MyData", MyDataTable, Nothing, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration)
  14.  
  15.         'Return the DataTable  
  16.         Return MyDataTable
  17.     Else
  18.         ' Return the cached version  
  19.         Return dt
  20.     End If
  21.  
  22. End Function


This Hack is part of the ASP.NET Hacks collection

432 Rating: 3.0/5 (1 vote cast)