using Microsoft.Extensions.Caching.Memory; IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); string key = "myKey"; string value = "myValue"; cache.Set(key, value); // Retrieving value from cache if (cache.TryGetValue(key, out string result)) { Console.WriteLine(result); }
using Microsoft.Extensions.Caching.Memory; IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); string key = "myKey"; string value = "myValue"; MemoryCacheEntryOptions cacheOptions = new MemoryCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddSeconds(30) }; cache.Set(key, value, cacheOptions); // Wait for 30 seconds for cache to expire Thread.Sleep(30000); // Now try to retrieve value again if (!cache.TryGetValue(key, out string result)) { Console.WriteLine("Value has expired"); }In this example, we add an expiration time to the cache entry using the `MemoryCacheEntryOptions`. We then wait for 30 seconds before trying to retrieve the value again. Since the cache entry has expired, the `TryGetValue()` method returns false. CacheHelper is a popular package/library provided by Microsoft in C# and is part of the Microsoft.Extensions.Caching namespace.