title: How can I lock by cache key?
body: <p>I am trying to implement a generic thread-safe Cache method, and I wonder how I should implement the lock in it.</p>
  
  <p><b>It should look something like this:</b></p>
  
  <pre><code>//private static readonly lockObject = new Object();
  
  public T GetCache&lt;T&gt;(string key, Func&lt;T&gt; valueFactory...)
  {
  
    // try to pull from cache here
  
    lock (lockObject) // I don't want to use static object lock here because then every time a lock is performed, all cached objects in my site have to wait, regarding of the cache key.
    {
      // 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
  
  }
  </code></pre>