I'm using Enterprise Library Caching for my MVC3 application.
My code is something like this:
object myLock = new Object();
public static MyEntity[] getMyEntities()
{
MyEntity[] res;
res = getMyEntities(new GetMyEntitiesRefreshAction());
return res;
}
private class GetMyEntitiesRefreshAction : ICacheItemRefreshAction
{
public void Refresh(string removedKey, object expiredValue, CacheItemRemovedReason removalReason)
{
getMyEntitiesInCache(this);
}
}
private static MyEntity[] getMyEntitiesInCache(ICacheItemRefreshAction action)
{
ICacheManager defaultCache = EnterpriseLibraryContainer.Current.GetInstance<ICacheManager>();
MyEntity[] result;
lock (myLock)
{
if ((result = defaultCache.GetData("myEntities") as MyEntity[]) == null)
{
using (EntityContext _entities = new EntityContext())
{
res = _entities.MyEntity
.Include("A.B.C")
.Include("A.B.D")
.Include("A.B.E")
.Include("A.B.F.G")
.Include("A.B.H.I.J")
.Include("A.B.K.L")
.Include("A.B.K.M")
.Include("A.B.N.O")
.Where(x => x.Active && x.Type == 1).ToArray();
//this query takes 20 seconds or more
}
defaultCache.Add("myEntities", result, CacheItemPriority.High, action, new AbsoluteTime(new TimeSpan(0, 1, 0)));
}
}
return result;
}
So, when someone calls getMyEntities, and elements are cached, there's no problem. But when elements are expired or are being loaded into the cache, users have to wait a long time before they see some results. Is there a way to always return something INSTANTLY? If I'm executing the query I would like to return the expired object so that users don't have to wait, and when query completes, I would just keep the new results. Any ideas?