1

我正在为我的 MVC3 应用程序使用企业库缓存。

我的代码是这样的:

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;
        }

因此,当有人调用 getMyEntities,并且缓存了元素时,就没有问题了。但是当元素过期或正在加载到缓存中时,用户必须等待很长时间才能看到一些结果。有没有办法总是立即返回一些东西?如果我正在执行查询,我想返回过期的对象,这样用户就不必等待,当查询完成时,我只会保留新的结果。有任何想法吗?

4

0 回答 0