title: Performance Counter - System.InvalidOperationException: Category does not exist
body: <p>I have following class that returns number of current Request per Second of IIS. I call RefreshCounters every minute in order to keep Requests per Second value refreshed (because it is average and if I keep it too long old value will influence result too much)... and when I need to display current RequestsPerSecond I call that property.</p>
  
  <pre><code>public class Counters
  {
      private static PerformanceCounter pcReqsPerSec;
      private const string counterKey = "Requests_Sec";
      public static object RequestsPerSecond
      {
          get
          {
              lock (counterKey)
              {
                  if (pcReqsPerSec != null)
                      return pcReqsPerSec.NextValue().ToString("N2"); // EXCEPTION
                  else
                      return "0";
              }
          }
      }
  
      internal static string RefreshCounters()
      {
          lock (counterKey)
          {
              try
              {
                  if (pcReqsPerSec != null)
                  {
                      pcReqsPerSec.Dispose();
                      pcReqsPerSec = null;
                  }
  
                  pcReqsPerSec = new PerformanceCounter("W3SVC_W3WP", "Requests / Sec", "_Total", true);
                  pcReqsPerSec.NextValue();
  
                  PerformanceCounter.CloseSharedResources();
  
                  return null;
              }
              catch (Exception ex)
              {
                  return ex.ToString();
              }
          }
      }
  }
  </code></pre>
  
  <p>The problem is that following Exception is <em>sometimes</em> thrown:</p>
  
  <pre><code>System.InvalidOperationException: Category does not exist.
  
  at System.Diagnostics.PerformanceCounterLib.GetCategorySample(String machine,\ String category)
  at System.Diagnostics.PerformanceCounter.NextSample()
  at System.Diagnostics.PerformanceCounter.NextValue()
  at BidBop.Admin.PerfCounter.Counters.get_RequestsPerSecond() in [[[pcReqsPerSec.NextValue().ToString("N2");]]]
  </code></pre>
  
  <p>Am I not closing previous instances of PerformanceCounter properly? What am I doing wrong so that I end up with that exception sometimes?</p>
  
  <p><strong>EDIT:</strong>
  And just for the record, I am hosting this class in IIS website (that is, of course, hosted in App Pool which has administrative privileges) and invoking methods from ASMX service. Site that uses Counter values (displays them) calls RefreshCounters every 1 minute and RequestsPerSecond every 5 seconds; RequestPerSecond are cached between calls.</p>
  
  <p>I am calling RefreshCounters every 1 minute because values tend to become "stale" - too influenced by older values (that were actual 1 minute ago, for example).</p>