title: Naming multi-instance performance counters in .NET
body: <p>Most multiple instance performance counters in Windows seem to automatically(?) have a #n on the end if there's more than one instance with the same name.</p>
  
  <p>For example: if, in Perfmon, you look under the <code>Process</code> category, you'll see:</p>
  
  <pre><code>...
  dwm
  explorer
  explorer#1
  ...
  </code></pre>
  
  <p>I have two <code>explorer.exe</code> processes, so the second counter has #1 appended to its name.</p>
  
  <p>When I attempt to do this in a .NET application:</p>
  
  <ul>
  <li>I can create the category, and register the instance (using the <code>PerformanceCounterCategory.Create</code> that takes a <code>CounterCreationDataCollection</code>).</li>
  <li>I can open the counter for write and write to it.</li>
  </ul>
  
  <p>When I open the counter a second time (in another process), it opens the same counter. This means that I have two processes fighting over the counters.</p>
  
  <p>The <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.instancename.aspx" rel="noreferrer">documentation for <code>PerformanceCounter.InstanceName</code></a> states that <code>#</code> is not allowed in the name.</p>
  
  <p>So: how do I have multiple-instance performance counters that are actually multiple instance? And where the second (and subsequent) instances get <code>#n</code> appended to the name?</p>
  
  <p>That is: I know that I can put the process ID (e.g.) on the instance name. This works, but has the unfortunate side effect that restarting the process results in a new PID, and Perfmon continues monitoring the old counter.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>I'm creating the category (and counter) as follows:</p>
  
  <pre><code>const string categoryName = "Test App";
  const string counterName = "Number of kittens";
  string instanceName =
      Path.GetFileNameWithoutExtension(
          Process.GetCurrentProcess().MainModule.FileName);
  
  if (!PerformanceCounterCategory.Exists(categoryName))
  {
      var counterCreationDataCollection = new CounterCreationDataCollection
          {
              new CounterCreationData(counterName, "",
                  PerformanceCounterType.NumberOfItems32)
          };
  
      PerformanceCounterCategory.Create(categoryName, "",
          PerformanceCounterCategoryType.MultiInstance,
          counterCreationDataCollection);
  }
  </code></pre>
  
  <p>I'm opening the counter as follows:</p>
  
  <pre><code>PerformanceCounter counter = new PerformanceCounter(
          categoryName, counterName, instanceName, readOnly: false);
  </code></pre>