What is the best way to lock cache in asp.net?

前端 未结 10 711
悲&欢浪女
悲&欢浪女 2020-11-27 09:33

I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resourc

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 10:18

    I saw one pattern recently called Correct State Bag Access Pattern, which seemed to touch on this.

    I modified it a bit to be thread-safe.

    http://weblogs.asp.net/craigshoemaker/archive/2008/08/28/asp-net-caching-and-performance.aspx

    private static object _listLock = new object();
    
    public List List() {
        string cacheKey = "customers";
        List myList = Cache[cacheKey] as List;
        if(myList == null) {
            lock (_listLock) {
                myList = Cache[cacheKey] as List;
                if (myList == null) {
                    myList = DAL.ListCustomers();
                    Cache.Insert(cacheKey, mList, null, SiteConfig.CacheDuration, TimeSpan.Zero);
                }
            }
        }
        return myList;
    }
    

提交回复
热议问题