小编典典

在asp.net中锁定缓存的最佳方法是什么?

c#

我知道在某些情况下,例如长时间运行的进程,锁定ASP.NET缓存很重要,这样可以避免其他用户对该资源的后续请求再次执行该长时间进程,而不是访问缓存。

用C#在ASP.NET中实现缓存锁定的最佳方法是什么?


阅读 276

收藏
2020-05-19

共1个答案

小编典典

这是基本模式:

  • 检查缓存中的值,如果可用则返回
  • 如果该值不在高速缓存中,则实施锁定
  • 在锁内,再次检查缓存,您可能已被阻止
  • 执行值查找并将其缓存
  • 释放锁

在代码中,它看起来像这样:

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

}
2020-05-19