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. Reference: http://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. 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. This is the 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.
Related posts
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.
We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.
Sign in