Caching Support All Types of .NET 4.0 Application


In early .NET versions if someone asked, can we implement caching in a Console Application, Windows Presentation Foundation Application, and other .NET Applications other than ASP.NET application then people would laugh at this question but now with .NET 4.0 and above framework, we can cache data in all types of .NET applications such as Console Applications, Windows Forms, and Windows Presentation Application, etc.
Let's see what is a new thing in the .NET 4.0 framework. They introduce a new library System.Runtime.Caching that implements caching for all types of .NET applications.
Let's try to implement caching in a Console Application.
Step 1: First of all we will create a new Console Application. I have given it the name SystemRuntimeCachingSample40.
Step 2: Now we will try to add a System.Runtime.Caching assembly to our project but unfortunately, you will not find that assembly because by default your target framework is .NET Framework 4 Client Profile.
You must change it from the client profile to .NET framework 4.
Now you can find the assembly; see the following image:
Step 3: Now everything is set up.
Let's write code for caching.
  1. static void Main(string[] args)  
  2. {  
  4.     for (int i = 0; i < 2; i++)  
  5.     {   
  6.         ObjectCache cache = MemoryCache.Default;  
  7.         CacheItem fileContents = cache.GetCacheItem("filecontents");  
  8.         if (fileContents == null)  
  9.         {  
  10.             CacheItemPolicy policy = new CacheItemPolicy();  
  11.             List<string> filePaths = new List<string>();  
  12.             string cachedFilePath = @"C:\Users\amitpat\Documents\cacheText.txt";  
  13.             filePaths.Add(cachedFilePath);  
  14.             policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));  
  15.             string fileData = File.ReadAllText(cachedFilePath);  
  16.             fileContents = new CacheItem("filecontents", fileData);  
  17.             cache.Set(fileContents, policy);   
  18.        }  
  19.          Console.WriteLine(fileContents.Value as string);  
  20.      }   
  21.     Console.Read();   
When you run your application you will see that for the second time it will not go into the IF block.
Happy Coding