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 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.

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";


            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);


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

Happy Coding