Caching Support All Types of .NET 4.0 Application

Introduction

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.

Referencehttp://msdn.microsoft.com/en-us/library/dd985642

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.

Caching1.png

Caching2.png

You must change it from client profile to .NET famework 4.

Caching3.png
 

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

Caching4.png
 
Step 3: Now everything is set up.

Let's write code for caching.

static void 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 = new List<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 as string);

     } 
    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

Up Next
    Ebook Download
    View all
    Learn
    View all