I have implemented in-memory cache in .NET application without any expiration token. For some reason, the cache evicted by external proccess. At first I thought it happens because the Application Pool Recycling , thats true, and for that reason i set him to 6:00 am. Still, the cache evicted but not consistent. thats one of the functions that releated to some controller. Thanks in advance
namespace webApiService.Controllers {
public class DBStore {
private const string presenceKey = "presence";
private readonly ConcurrentDictionary<object, SemaphoreSlim> locks = new ConcurrentDictionary<object, SemaphoreSlim>();
private readonly ConcurrentDictionary<object, SemaphoreSlim> fileLocks = new ConcurrentDictionary<object, SemaphoreSlim>();
private readonly flexWHContext _context;
bool fromCache = false;
public DBStore(IMemoryCache memoryCache,flexWHContext context) {
this.memoryCache = memoryCache;
_context = context;
}
public async Task<List<Presence>> getPresence() {
fromCache = false;
if (!(fromCache = memoryCache.TryGetValue(presenceKey, out List<Presence> presence))) {
SemaphoreSlim certLock = locks.GetOrAdd(presenceKey, k => new SemaphoreSlim(1, 1));
await certLock.WaitAsync();
try {
if (!memoryCache.TryGetValue(presenceKey, out presence)) {
System.IO.File.AppendAllText(@"C:\Users\spdev\Desktop\WriteText.txt", "getPresence - not in cache "+ DateTime.Now + Environment.NewLine);;
presence = await _context.Presence.FromSqlRaw("SHP_SP_Presence").AsNoTracking().ToListAsync();
System.IO.File.AppendAllText(@"C:\Users\spdev\Desktop\WriteText.txt", "getPresence - set in cache" + Environment.NewLine);
//memoryCache.Set(presenceKey, presence, GetMemoryCacheEntryOptions());
memoryCache.Set(presenceKey, presence);
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
System.IO.File.AppendAllText(@"C:\Users\spdev\Desktop\WriteText.txt", "lock releaes" + Environment.NewLine+ Environment.NewLine);
certLock.Release();
}
}
if (fromCache) {
System.IO.File.AppendAllText(@"C:\Users\spdev\Desktop\WriteText.txt", "getPresence - bring from cache " + DateTime.Now + Environment.NewLine);
}
return presence;
}