0

我在 .NET 应用程序中实现了内存缓存,没有任何过期令牌。由于某种原因,缓存被外部进程驱逐。起初我认为这是因为应用程序池回收,这是真的,因此我将他设置为早上 6:00。尽管如此,缓存被驱逐但不一致。那是与某些控制器相关的功能之一。提前致谢

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;
    }
4

0 回答 0