To improve performance in my ASP.Net site I am caching collections of entities.
Below is some code that checks if the cache is populated, if it is then it returns the collection after performing "CacheClean" which resets certain properties so even if they were modified from another request they will be reset. If not then an entity query is ran and the cache is set.
MemoryCache cache = MemoryCache.Default;
List<MyControl> controlList = cache["ControlListByType" + TypeId] as List<MyControl>;
if (controlList == null)
{
myDbContext.Configuration.ProxyCreationEnabled = false;
myDbContext.Configuration.LazyLoadingEnabled = false;
controlList = myDbContext.MyControls.AsNoTracking()
.Include(c => c.ControlComboBoxes)
.Include(c => c.ControlComments)
.Include(c => c.ControlItems)
.Include(c => c.ControlType)
.Include(c => c.ControlUploads)
.Where(c => c.TypeId == TypeId).OrderBy(c => c.Position)
.ToList();
cache["ControlListByType" + TypeId] = controlList;
}
else
controlList.ForEach(c => c.CacheClean());
return controlList;
My issue is that when processing the request these objects in the collection will be modified so if multiple users try to access the cache at the same time they could potentially overwrite each other and errors will occur or the View will be generated incorrectly.
So I am looking for a way to flag the cache entry as In use when accessed so that the cache is only used when populated and not in use, and then release it at the end of the request.