I want to get some performance counters for the "ASP.NET Applications" category from my ASP.NET application.
My problem is that I do not know how to determine the correct instance name for my current ASP.NET application.
I am currently using this 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));
For GetCurrentProcessInstanceName, I determined these helper methods from the information and code snippets that I found on the tubes:
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; }
Now the problem is that I get the following error: Instance "w3wp" does not exist in the specified category.
Thus, it is obvious that the code fragments do not return the correct instance ID for the current application.
My question is: How can I determine the (reliable) correct value?
Additional information: Since I learned that you first need to create a performance counter object and reuse this instance (against creating this object in every case in which it is necessary). I run singleton when the application starts. For this reason, I do not have access to the current HttpRequest, since this happens before the request gets into the application.