Skip to content

Instantly share code, notes, and snippets.

@JsAndDotNet
Created March 29, 2022 08:49
Show Gist options
  • Save JsAndDotNet/594019f4053a498aef3e0fcd59f5c68d to your computer and use it in GitHub Desktop.
Save JsAndDotNet/594019f4053a498aef3e0fcd59f5c68d to your computer and use it in GitHub Desktop.
Caching in .NET6+ Using IMemoryCache - Console Example
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using System;
namespace CacheTest
{
public class CacheHelper
{
private IMemoryCache _memoryCache { get; } = new MemoryCache(
new MemoryCacheOptions
{
SizeLimit = 1024, /* CHECK THIS IS THIS THE RIGHT SIZE FOR YOU! */
CompactionPercentage = .3,
ExpirationScanFrequency = TimeSpan.FromSeconds(30),
});
public bool AddToCache(string key, int expriryTimeInSeconds)
{
bool isSuccess = false;
if (!IsInCache(key))
{
var currntCount = ((MemoryCache)_memoryCache).Count;
Console.WriteLine("Cache Size: " + currntCount);
var cancellationTokenSource = new CancellationTokenSource(
TimeSpan.FromSeconds(3));
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSize(1)
.AddExpirationToken(
new CancellationChangeToken(cancellationTokenSource.Token));
_memoryCache.Set(key, DateTime.Now, cacheEntryOptions);
var currntCount2 = ((MemoryCache)_memoryCache).Count;
Console.WriteLine("New Cache Size: " + currntCount2);
isSuccess = true;
}
return isSuccess;
}
public bool AddToCache<T>(string key, T value, int expriryTimeInSeconds)
{
bool isSuccess = false;
if (!IsInCache(key))
{
var currntCount = ((MemoryCache)_memoryCache).Count;
Console.WriteLine("Cache Size: " + currntCount);
var cancellationTokenSource = new CancellationTokenSource(
TimeSpan.FromSeconds(expriryTimeInSeconds));
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(DateTimeOffset.Now.AddSeconds(expriryTimeInSeconds))
.SetSize(1)
.AddExpirationToken(
new CancellationChangeToken(cancellationTokenSource.Token));
_memoryCache.Set<T>(key, value, cacheEntryOptions);
var currntCount2 = ((MemoryCache)_memoryCache).Count;
Console.WriteLine("New Cache Size: " + currntCount2);
isSuccess = true;
}
return isSuccess;
}
public T GetFromCache<T>(string key)
{
return _memoryCache.Get<T>(key);
}
public bool IsInCache(string key)
{
var item = _memoryCache.Get(key);
return item != null;
}
}
}
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
CacheTest.CacheHelper cache = new CacheTest.CacheHelper();
var seconds = 3;
var key1 = "Test1";
Console.WriteLine("Should pass ");
if (cache.AddToCache(key1, seconds))
{
Console.WriteLine($"pass {key1}");
}
else
{
Console.WriteLine($"fail {key1}");
}
var key2 = "Test2";
Console.WriteLine("Should pass ");
if (cache.AddToCache(key2, seconds))
{
Console.WriteLine($"pass {key2}");
}
else
{
Console.WriteLine($"fail {key2}");
}
await Task.Delay(1000);
Console.WriteLine();
Console.WriteLine("Should fail ");
if (cache.AddToCache(key1, seconds))
{
Console.WriteLine($"pass {key1}");
}
else
{
Console.WriteLine($"fail {key1}");
}
Console.WriteLine("wait");
await Task.Delay(20000);
Console.WriteLine();
Console.WriteLine("Should pass ");
if (cache.AddToCache(key1, seconds))
{
Console.WriteLine($"pass {key1}");
}
else
{
Console.WriteLine($"fail {key1}");
}
Console.WriteLine("********************************************");
Console.WriteLine("********************************************");
Console.WriteLine("Press enter to start <T> test");
Console.ReadLine();
seconds = 3;
var key3 = "Test3";
Console.WriteLine("Should pass ");
if (cache.AddToCache<string>(key3, "test3value", seconds))
{
Console.WriteLine($"pass {key3}");
}
else
{
Console.WriteLine($"fail {key3}");
}
var val = cache.GetFromCache<string>(key3);
if (val == null)
{
Console.WriteLine($"{key3} is null - something is wrong");
}
else
{
Console.WriteLine($"{key3} = {val}. This is correct!");
}
var key4 = "Test4";
Console.WriteLine("Should pass ");
if (cache.AddToCache<string>(key4, "test4value", seconds))
{
Console.WriteLine($"pass {key4}");
}
else
{
Console.WriteLine($"fail {key4}");
}
await Task.Delay(1000);
Console.WriteLine();
Console.WriteLine("Should fail ");
if (cache.AddToCache<string>(key3, "test3value", seconds))
{
Console.WriteLine($"pass {key3}");
}
else
{
Console.WriteLine($"fail {key3}");
}
Console.WriteLine();
Console.WriteLine("wait");
await Task.Delay(20000);
var va2 = cache.GetFromCache<string>(key3);
if(va2 == null)
{
Console.WriteLine($"{key3} is null");
}
else
{
Console.WriteLine($"{key3} is has a value - this shouldn't happen!");
}
Console.WriteLine("Should pass ");
if (cache.AddToCache<string>(key3, "test3value", seconds))
{
Console.WriteLine($"pass {key3}");
}
else
{
Console.WriteLine($"fail {key3}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment