Caching Support All Types of .NET 4.0 Application

This article shows how to implement data caching in a Console Application, Windows Presentation Foundation Application and other .NET Applications other than ASP.NET application using the .NET 4.0 and above framework.

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.

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 client profile to .NET famework 4.

Now you can find the assembly; see the following image:

Step 3: Now everything is set up.

Let's write code for caching.

staticvoid Main(string[] args)

{

for (int i = 0; i < 2; i++)

{ ObjectCache cache = MemoryCache.Default;

CacheItem fileContents = cache.GetCacheItem("filecontents");

if (fileContents == null) {

CacheItemPolicy policy = new CacheItemPolicy();

List<string> filePaths = newList<string>();

string cachedFilePath = @"C:\Users\amitpat\Documents\cacheText.txt";

filePaths.Add(cachedFilePath);

policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));

string fileData = File.ReadAllText(cachedFilePath);

fileContents = new CacheItem("filecontents", fileData);

cache.Set(fileContents, policy);

}

Console.WriteLine(fileContents.Value asstring);

} Console.Read(); }

When you run your application you will see that for the second time it will not go into the IF block.