Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It should work. Note that as others have already set, the CLR counters are per instance counters, thus you need to specify the instance name for the process you wish to query the counters for.</p> <p>So the statement you specified at the top of your post should work. However, you should also use the constructor overload that allows you to specify that you wish to access the instance in "read-only" mode:</p> <pre><code>new PerformanceCounter(".NET CLR Memory", "# bytes in all heaps", Process.GetCurrentProcess().ProcessName, true); </code></pre> <p>The second code fragment you posted does not work, as you didn't specify an instance name to the <code>GetCounters()</code> operation. Use the <code>GetCounters(string instanceName)</code> overload instead and it should work.</p> <p>Finally, note that the instance name is not necessarily the same as <code>Process.ProcessName</code> (or <code>Process.GetCurrentProcess().ProcessName</code> for that matter). If there are multiple instances of a process, i.e. executable, the process name is created by appending a <code>#&lt;number&gt;</code>. To figure out the actual instance name of a process you should query the <code>.NET CLR Memory\Process ID</code> counter.</p> <p>Example:</p> <pre><code> public static string GetInstanceNameForProcessId(int pid) { var cat = new PerformanceCounterCategory(".NET CLR Memory"); foreach (var instanceName in cat.GetInstanceNames()) { try { using (var pcPid = new PerformanceCounter(cat.CategoryName, "Process ID", instanceName)) { if ((int)pcPid.NextValue() == pid) { return instanceName; } } } catch (InvalidOperationException) { // This may happen, if the PC-instance no longer exists between the // time we called GetInstanceNames() and the time we come around actually // try and use the instance. // In this situation that is not an error, so ignore it. } } throw new ArgumentException( string.Format("No performance counter instance found for process id '{0}'", pid), "pid"); } </code></pre> <p>The instance name you gather by this method is good for performance counters in other ".NET CLR" categories as well.</p> <p><strong>Update</strong>: Added mitigation for potential race condition between the time we gather the potential instance names and the time we peruse them. A .NET process (for which we've seen an instance name) might no longer be there (and such the instance is also gone) when we try to use it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload