Caching In WPF

Caching is one of the fundamental things that a developer should consider while developing large scale applications.

In this article, I have implemented a simple caching application that keeps track of the file changes on the hard disk and shows in a TextBlock (WPF application).

You can find the detailed references and methods on this link.

.NET framework provides an abstract class named ObjectCache class and Memory cache class (which is a concrete implementation of the ObjectCache class). I have used MemoryCache class to instantiate the ObjectCache reference and deal with the file data.

Take a look at the below example. I have TextBlock and a button. Aim is to read cache data and show it in the TextBlock.

TextBlock

Below is the code that I have implemented on Reload button click event.

As ObjectCache is an abstract class, you can do something like the following.

  1. ObjectCache cache = MemoryCache.Default;  
Basically, you can store the data into cache by providing name value pair. For example, to store the name in cache, you can use the above cache reference and do as:
  1. cache.Set(“name”, actual name, expiration policy)  
Note that saving or editing the null values using MemoryCache class will fail.

The third parameter is the driver for the cache which instructs CLR to remove/invalidate cache content after a certain period of time. The below code expires the cache content after 10 seconds. You can set the cache policy as:
  1. CacheItemPolicy policy = new CacheItemPolicy();  
  2. policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);  
The next step is to read from the cache if there is any content.
  1. string fcontent = cache["filecontent"as string;  
Now, when we start the application for the first time, there won’t be any cached content for our application. Hence, you can read the file content as below:
  1. String fcontent = File.ReadAllText(@"Your File path\test.txt")  
Once we have the content, you can set the cache content as:
  1. cache.Set("filecontent", fcontent, policy);  
Altogether, it looks like this:
  1. private void btnReloadCache_Click(object sender, RoutedEventArgs e) {  
  2.     ObjectCache cache = MemoryCache.Default;  
  3.     //try reading the cache content first. if null then make an entry  
  4.     string fcontent = cache["filecontent"as string;  
  5.     if (string.IsNullOrEmpty(fcontent)) {  
  6.         //create an item policy for   
  7.         CacheItemPolicy policy = new CacheItemPolicy();  
  8.         policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);  
  9.         List < string > filepath = new List < string > ();  
  10.         filepath.Add(@ "D:\Other\test.txt");  
  11.         policy.ChangeMonitors.Add(new HostFileChangeMonitor(filepath));  
  12.         fcontent = File.ReadAllText(@ "Your File path \test.txt") + "\n" + DateTime.Now;  
  13.         //adding items to cache with expiration policy and the object value  
  14.         cache.Set("filecontent", fcontent, policy);  
  15.     }  
  16.     textBlock.Text = fcontent;  
  17. }  
You should have a question like what is the deal with the list of strings and what is HostFileChangeMonitor. Well, .NET framework provides this class to monitor the file changes. The constructor of HostFileChangeMonitor accepts the list of paths and keeps track of folders or files. If there is any change in the file content, it notifies the cache and makes system to read that file again. Basically, I have created this monitor object, attached it to the cache expiration policy, and bound that policy to the cache object. So, when you run the application, you should see output similar to the following. Click on Reload button and it should load the content of the file to TextBlock.

Content of Text File

Content of Text File

Content of Text File

Now, this is something interesting.

Don’t close the application. Go to your test.txt file, change the text in that file, and save the content.
Now, go back to running the application and hit Reload button. This time, you would see that the content of the TextBlock got updated even though we didn’t close the application. It became possible because of HostFileChangeMonitor. Note the DateTime stamp to identify the latest results from cache.

Content of Text File

Content of Text File

The moment you go for saving the text file, HostFileChangeMonitor notifies the cache (invalidates the cache content) and make it read the same file content again. That’s how you can achieve the caching in WPF application.

Feel free to make suggestions/ask questions.

 

Up Next
    Ebook Download
    View all
    Learn
    View all