CS2-11: Добавлено обновление устаревших CacheTable при их вызове

This commit is contained in:
KharchenkoVV 2021-05-21 12:30:25 +05:00
parent 802fdd1015
commit 7b00cedb47
2 changed files with 18 additions and 6 deletions

View File

@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using System;
using Microsoft.EntityFrameworkCore;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -7,7 +8,8 @@ namespace AsbCloudInfrastructure.Services.Cache
public class CacheDb
{
private readonly ConcurrentDictionary<string, IEnumerable<object>> cache = new ConcurrentDictionary<string, IEnumerable<object>>();
private readonly ConcurrentDictionary<string, (DateTime, IEnumerable<object>)> cache = new ConcurrentDictionary<string, (DateTime, IEnumerable<object>)>();
private readonly TimeSpan obsolesenceTime = TimeSpan.FromMinutes(15);
public CacheTable<TEntity> GetCachedTable<TEntity>(DbContext context)
where TEntity : class
@ -15,9 +17,15 @@ namespace AsbCloudInfrastructure.Services.Cache
var entityTypeName = typeof(TEntity).FullName;
if (!cache.ContainsKey(entityTypeName))
cache[entityTypeName] = new List<TEntity>(8);
cache[entityTypeName] = (DateTime.Now, new List<TEntity>(8));
bool isCachedDataObsolete = DateTime.Now - cache[entityTypeName].Item1 > obsolesenceTime;
var tableCache = new CacheTable<TEntity>(context, cache[entityTypeName]);
if (isCachedDataObsolete)
tableCache.Refresh();
var tableCache = new CacheTable<TEntity>(context, (List<TEntity>)cache[entityTypeName]);
return tableCache;
}

View File

@ -10,12 +10,14 @@ namespace AsbCloudInfrastructure.Services.Cache
public class CacheTable<TEntity> where TEntity : class
{
private readonly DbContext context;
private (DateTime refreshDate, IEnumerable<object> entities) data;
private readonly List<TEntity> cached;
internal CacheTable(DbContext context, List<TEntity> entities)
internal CacheTable(DbContext context, (DateTime refreshDate, IEnumerable<object> entities) data)
{
this.context = context;
this.cached = entities;
this.data = data;
this.cached = (List<TEntity>)data.entities;
}
public TEntity this[int index] { get => cached.ElementAt(index); }
@ -25,6 +27,7 @@ namespace AsbCloudInfrastructure.Services.Cache
cached.Clear();
var dbEntities = context.Set<TEntity>().ToList();
cached.AddRange(dbEntities);
data.refreshDate = DateTime.Now;
return cached.Count;
}
@ -33,6 +36,7 @@ namespace AsbCloudInfrastructure.Services.Cache
cached.Clear();
var dbEntities = await context.Set<TEntity>().ToListAsync(token).ConfigureAwait(false);
cached.AddRange(dbEntities);
data.refreshDate = DateTime.Now;
return cached.Count;
}