简体   繁体   English

ASP.NET缓存-长时间运行的操作

[英]ASP.NET Cache - long running operation

I'm storing data in cache as not to hit the database constantly (doesn't matter if the data is a little stale), the dataset isn't particularly large but the operation can take some time due to the complexity of the query (lot's of joins and sub queries). 我将数据存储在缓存中是为了避免持续访问数据库(数据是否过时也没关系),数据集不是特别大,但是由于查询的复杂性,操作可能需要一些时间(大量的联接和子查询)。 I have a static helper class and the data is used for binding on individual pages. 我有一个静态的帮助程序类,该数据用于在各个页面上进行绑定。 The page calls it like so: 该页面的调用方式如下:

public static List<MyList> MyDataListCache
        {
            get
            {
                var myList = HttpContext.Current.Cache["myList"];

                if (myList == null)
                {


                    var result = MyLongRunningOperation();

                        HttpContext.Current.Cache.Add("myList", result, null, DateTime.Now.AddMinutes(3),
                            Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);



                        return result;
                    }
                }
                else
                {
                    return (List<MyList>)myList;
                }
            }
        }

This works fine unless lot's of people hit the page at the same time when the item is out of cache. 除非很多人在该项目不在缓存中时同时点击该页面,否则此方法就很好。 Hundreds of the LongRunningOperations are spun up and cause the application to crash. 数百个LongRunningOperations被旋转并导致应用程序崩溃。 How do I avoid this problem? 如何避免这个问题? I've tried using async tasks to subscribe to if the task is currently running but had no luck in getting it to work. 我尝试使用异步任务来订阅该任务是否正在运行,但是没有运气。

Upon starting this service, you should call LongRunningOperation() immediately to warm up your cache. 启动此服务后,应立即调用LongRunningOperation()来预热缓存。

Second, you always want something to be returned, so I would consider a background task to refresh this cache prior to it's expiry. 其次,您始终希望返回某些内容,因此我将考虑执行后台任务以在此缓存过期之前刷新该缓存。

Doing these two things will void the situation you described. 做到这两点会使您所描述的情况无效。 The cache will be refreshed by a backgroundworker, and so everyone is happy :) 缓存将由后台工作人员刷新,因此每个人都很高兴:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM