title: locking object in async operation
body: <p>I have the following code that I want to achieve the following with. </p>
  
  <ol>
  <li>Check if a value is in cache</li>
  <li>If in cache, get the value from it and proceed</li>
  <li>If not in cache, perform the logic to enter it in cache but do this async as the operation to do such may take a long period of time and I dont want to hold up the user</li>
  </ol>
  
  <p>As you will see in my code I place a lock on the cache in the async thread. Is my setup below thread safe? And by placing the lock will this mean that the cache will not be accessible for other threads to read from cache while the async operation takes place. I do not want a circumstance where the cache is locked in an async thread preventing other requests from accessing it. </p>
  
  <p>There is also a chance that the same request may be called by several threads hence the lock.</p>
  
  <p>Any recommendations as how I could improve the code would be great.</p>
  
  <pre><code>// Check if the value is in cache
          if (!this.Cache.Contains(key))
          {
              // Perform processing of files async in another thread so rendering is not slowed down
              ThreadPool.QueueUserWorkItem(delegate
              {
                  lock (this.Cache)
                  {
                      if (!this.Cache.Contains(key))
                      {
                          // Perform the operation to get value for cache here
                          var cacheValue = operation();
  
                          this.Cache.Add(key, cacheValue);
                      }
                  }
              });
  
              return "local value";
          }
          else
          {
              // Return the string from cache as they are present there
              return this.Cache.GetFilename(key);
          }
  </code></pre>
  
  <p>Note: this.Cache represents a cache object.</p>
  
  <p>The application is a web application on .net 3.5.</p>