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

前端 未结 10 717
悲&欢浪女
悲&欢浪女 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:08

    Here's the basic pattern:

    • Check the cache for the value, return if its available
    • If the value is not in the cache, then implement a lock
    • Inside the lock, check the cache again, you might have been blocked
    • Perform the value look up and cache it
    • Release the lock

    In code, it looks like this:

    private static object ThisLock = new object();
    
    public string GetFoo()
    {
    
      // try to pull from cache here
    
      lock (ThisLock)
      {
        // cache was empty before we got the lock, check again inside the lock
    
        // cache is still empty, so retreive the value here
    
        // store the value in the cache here
      }
    
      // return the cached value here
    
    }
    

提交回复
热议问题