Thursday, November 24

HttpRuntime.Cache in Windows Application

I read a great tip on Scott Hanselman's Blog.

You can use the Cache class from within a windows application just as easily as a web application. This will be a lot more powerful than caching objects into a global Hashtable, as expiration policies can be set to ensure you don't use too many resources, and dependencies can be set using the CacheDependency class, forcing cached objects to be reloaded if something happens in the environment.

If you get an error Unable to load DLL (aspnet_isapi.dll), you can load the Cassini web server from here.

Here is some code to set up a cache with a dependency file:


private void button1_Click(object sender,
System.EventArgs e)
{
// Set cache

CacheDependency dependency =
new CacheDependency("c:\\temp\\b.txt");
String cached = "cached";
Cache cc = HttpRuntime.Cache;
cc.Remove("a");
cc.Insert("a", cached, dependency);
}

private void button2_Click(object sender,
System.EventArgs e)
{
// Display cache

Cache cc = HttpRuntime.Cache;
String c = (String)(cc["a"]);
label1.Text = c;
}

private void button3_Click(object sender,
System.EventArgs e)
{
// Change dependency file

StreamWriter s = System.IO.File.CreateText
("c:\\temp\\b.txt");
s.WriteLine("a");
s.Flush();
s.Close();

// Cache should be reset to nothing next
time you click button 2
}

3 comments:

Anonymous said...

Please tell me how to cache data as well as Controls in windows application.

Anonymous said...

Please tell me how to cache data as well as Controls in windows application.

Richard Jonas said...

The cached can contain anything derived from System.Object, so you should be able to put Datasets or anything like that in it.

You might also want to search for asynchronous callbacks if you are using SQL server 2005 - this will tell you if the data in the database has changed and allow you to remove your cached copy and force it to be reloaded.