The following code was born out of boredom on the DART this morning somewhere between Sydney Parade and Blackrock on my way to work. Its an enhanced version of my original file caching code that uses Cache Dependencies. Basically, if the file you've cached changes ASP.NET will remove the file from cache, so that the code can reload it on its next call.
Public Function strGetFile(ByVal strFilePath As String) As String
Dim strRetVal As String = Cache(strFilePath)
If strRetVal = vbNullString Then
Dim objStreamReader As StreamReader = File.OpenText(strFilePath)
strRetVal = objStreamReader.ReadToEnd()
Dim objDepend As New Caching.CacheDependency(strFilePath)
Cache.Insert(strFilePath, strRetVal, objDepend)
To demonstrate the usefulness of this code, try it out with a very large file, with code something like this:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Response.Write("Start Time : " & Now & " ... ")
Response.Write("End Time : " & Now & " ... ")
Simply create some large file somewhere, ensure the ASP.NET worker process has access to the folder and then browse to your ASPX page. Unless your system is lighning fast you'll see some delay before the page is displayed to the browser. ASP.NET has just loaded the file from the drive and cached it. You'll also see the time difference. Now try refreshing the page. ASP.NET has just loaded the file directly from cache.
If you modify the contents of the file in any way ASP.NET will remove it from cache and as such cause it to be reloaded from the drive on the next call.
The advantages and disadvantages are obvious. Advantages being faster page execution, and also extension of the lifespan of your disk drives. Disadvantage being that of memory usage - but hey, with no server shipping with less than 1GB of RAM these days, is that really an issue?