fix add SemaphoreSlim into Cache.Refresh(..) and Cache.RefreshAsync(..) method to avoid racing

This commit is contained in:
Фролов 2021-08-20 12:45:26 +05:00
parent 0e586edcc5
commit 9d50f0d1c9

View File

@ -13,6 +13,7 @@ namespace AsbCloudInfrastructure.Services.Cache
private (DateTime refreshDate, IEnumerable<object> entities) data;
private readonly List<TEntity> cached;
private readonly DbSet<TEntity> dbSet;
private readonly SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
internal CacheTable(DbContext context, (DateTime refreshDate, IEnumerable<object> entities) data)
{
@ -27,7 +28,10 @@ namespace AsbCloudInfrastructure.Services.Cache
public int Refresh()
{
if (cached.Any())
{
semaphore.Wait();
cached.Clear();
}
var dbEntities = context.Set<TEntity>().AsNoTracking().ToList();
cached.AddRange(dbEntities);
data.refreshDate = DateTime.Now;
@ -37,7 +41,10 @@ namespace AsbCloudInfrastructure.Services.Cache
public async Task<int> RefreshAsync(CancellationToken token = default)
{
if (cached.Any())
cached.Clear();
{
await semaphore.WaitAsync(token).ConfigureAwait(true);
cached.Clear();
}
var dbEntities = await context.Set<TEntity>().AsNoTracking().ToListAsync(token).ConfigureAwait(false);
cached.AddRange(dbEntities);
data.refreshDate = DateTime.Now;