5 Minutes .NET–Memory Cache
At https://youtu.be/BL5yo_p7x-E you can find the new video about caching in .NET with Memory Cache.
The code is:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace MemoryCacheNet { public static class GlobalData { static object lockMe = new object(); public static List<string> CountryList() { string key = "countries"; var data = MemoryCache.Default.Get(key) as List<string>; if(data == null) { lock (lockMe) { data = MemoryCache.Default.Get(key) as List<string>; if(data != null) { return data ; } data = CountryListFromDatabase(); var duration = DateTimeOffset.UtcNow.AddSeconds(5); MemoryCache.Default.AddOrGetExisting(key,data,duration); } } return data; } static List<string> CountryListFromDatabase() { Console.WriteLine("obtaining data from database"); return new List<string>() { "Romania", "India", "USA" // add your country 😉 }; } } }
and using from Console:
using MemoryCacheNet; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MemoryCacheDOS { class Program { static void Main(string[] args) { var data = GlobalData.CountryList(); Console.WriteLine(data.Count); Console.WriteLine("waiting 1 sec"); Thread.Sleep(1000); data = GlobalData.CountryList(); Console.WriteLine(data.Count); Console.WriteLine("waiting 5 sec"); Thread.Sleep(5000); data = GlobalData.CountryList(); Console.WriteLine(data.Count); } } }
Other tutorials are:
5MinThrowVsThrowEx
5Min Usefull Attributes
5MinIValidatableObject
5MinAsyncException
5MinAsync
5Min iMacrosAHK
5min Zip
5MinPSR
5MinParseWebPage
5MinFileHelpers
5Min Logging
5min Send emails and SMTP4Dev
5Min Memory Profiler ( User Object and/or memory leaks)
5min SFHB
5min – .TT files in Visual Studio
The full list is at https://www.youtube.com/playlist?list=PL4aSKgR4yk4OnmJW6PlBuDOXdYk6zTGps .
Its 5 second memorycache not 5 minut 😉
Right 😉
Thanks for this post, Andrei. Helped me a lot!