title: How to retrieve performance counter for current asp.net application
body: <p>I want to retrieve some performance counters for the 'ASP.NET Applications' category from within my ASP.NET application.</p>
  
  <p>My problem is, that I don't know how to determine the correct instance name for my current running ASP.NET application.</p>
  
  <p>I currently use this code:</p>
  
  <pre><code>string instanceName = GetCurrentProcessInstanceName();
  
  _perfCounters.Add(new PerformanceCounter("ASP.NET", "Application Restarts"));
  _perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Pipeline Instance Count", instanceName));
  _perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Requests Executing", instanceName));
  _perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Requests/Sec", instanceName));
  _perfCounters.Add(new PerformanceCounter("ASP.NET Applications", "Requests Failed", instanceName));
  </code></pre>
  
  <p>For GetCurrentProcessInstanceName I defined those helper methods from information and code snippets I found on the intertubes:</p>
  
  <pre><code>    private static string GetCurrentProcessInstanceName()
      {
          return GetProcessInstanceName(GetCurrentProcessId());
      }
  
      private static int GetCurrentProcessId()
      {
          return Process.GetCurrentProcess().Id;
      }
  
      private static string GetProcessInstanceName(int pid)
      {
          PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");
  
          string[] instances = cat.GetInstanceNames();
          foreach (string instance in instances)
          {
  
              using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true))
              {
                  int val = (int) cnt.RawValue;
                  if (val == pid)
                  {
                      return instance;
                  }
              }
          }
  
          return null;
      }
  </code></pre>
  
  <p>Now the problem is, that I get the following error:
  <strong>Instance 'w3wp' does not exist in the specified Category.</strong></p>
  
  <p>So obviously, the code snippets don't return the correct instance ID for the current application.</p>
  
  <p>My question is: <strong>How can I determine (reliable) the correct value?</strong></p>
  
  <p>Additional information:
  Since I learned that one should initially create a performance counter object and re-use this instance (vs. creating this object on every occasion you need this) I fire up a singleton when the application starts up. Out of this reason, I don't have access to a current HttpRequest, since this happens before a request hits the application.</p>