title: How should I make my hashtable cache implementation thread safe when it gets cleared?
body: <p>I have a class used to cache access to a database resource. It looks something like this:</p>
  
  <pre><code>//gets registered as a singleton
  class DataCacher&lt;T&gt;
  {
      IDictionary&lt;string, T&gt; items = GetDataFromDb();
  
      //Get is called all the time from zillions of threads
      internal T Get(string key)
      {
           return items[key];
      }
  
      IDictionary&lt;string, T&gt; GetDataFromDb() { ...expensive slow SQL access... }
  
      //this gets called every 5 minutes
      internal void Reset()
      {
            items.Clear();
      }
  }
  </code></pre>
  
  <p>I've simplified this code somewhat, but the gist of it is that there is a potential concurrency issue, in that while the items are being cleared, if Get is called things may go awry.</p>
  
  <p>Now I can just bung lock blocks into Get and Reset, but I'm worried that the locks on the Get will reduce performance of the site, as Get is called by every request thread in the web app many many times. </p>
  
  <p>I can do something with a doubly checked locks I think, but I suspect there is a cleaner way to do this using something smarter than the lock{} block. What to do?</p>
  
  <p>edit: Sorry all, I didn't make this explicit earlier, but the items.Clear() implementation I am using is not in fact a straight dictionary. Its a wrapper around a ResourceProvider which requires that the dictionary implementation calls .ReleaseAllResources() on each of the items as they get removed. This means that calling code doesn't want to run against an old version that is in the midst of disposal. Given this, is the Interlocked.Exchange method the correct one?</p>