Ho un progetto con core asp.net e core framework di entità, per motivi di prestazioni utilizzo MemoryCache. La classe ForumQueryManager è per interrogare i dati del forum e questa classe per i dati utilizza il metodo CacheManager Get e passa cachekey e timeout della cache timeout e un metodo per quando la cache è vuota per il recupero dei dati dal database. questo codice funziona quasi sempre. ma a volte genera un'eccezione
Eccezione:
Si è verificata un'eccezione non gestita durante l'elaborazione della richiesta. InvalidOperationException: una seconda operazione avviata in questo contesto prima che fosse completata un'operazione precedente. Non è garantito che tutti i membri di istanza siano thread-safe.
Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection ()
ForumQueryManager:
public class ForumQueryManager : IForumQueryManager
{
private readonly NashrNegarDbContext _dbContext;
private readonly ICalender _calender;
private readonly ICacheManager _cacheManager;
public ForumQueryManager(NashrNegarDbContext dbContext, ICacheManager cacheManager)
{
_dbContext = dbContext;
_cacheManager = cacheManager;
}
public async Task<List<ForumCategoryDto>> GetAll()
{
var items = await _cacheManager.Get(CacheConstants.ForumCategories, 20, GetForumCategories);
return items;
}
private async Task<List<ForumCategoryDto>> GetForumCategories()
{
var categories = await _dbContext.ForumCategories
.Select(e => new ForumCategoryDto
{
Name = e.Name,
ForumCategoryId = e.ForumCategoryId
}).ToListAsync();
return categories;
}
}
CacheManager:
public class CacheManager: ICacheManager
{
private readonly IMemoryCache _cache;
private readonly CacheSetting _cacheSetting;
public CacheManager(IMemoryCache cache, IOptions<CacheSetting> cacheOption)
{
_cache = cache;
_cacheSetting = cacheOption.Value;
}
public async Task<List<T>> Get<T>(string cacheKey, int expirationMinutes, Func<Task<List<T>>> function)
{
List<T> items;
if (_cacheSetting.MemeoryEnabled)
{
var value = _cache.Get<string>(cacheKey);
if (value == null)
{
items = await function();
value = JsonConvert.SerializeObject(items, Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
_cache.Set(cacheKey, value,
new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(expirationMinutes)));
}
else
{
items = JsonConvert.DeserializeObject<List<T>>(value);
}
}
else
{
items = await function();
}
return items;
}
}
ForumQueryManager
deve essere transitorio, altrimenti la variabile _dbContext
verrà riutilizzata.