Nov 27, 2015

Performance Counters on ASP.NET

If you want to use performance counters on your ASP.NET page you can use  System.Diagnostics.PerformanceCounter class. Example below shows running inside a generic handler.

static System.Diagnostics.PerformanceCounter cpuUsage;

public void ProcessRequest(HttpContext context)
    context.Response.ContentType = "text/plain";
    if (cpuUsage == null)
        cpuUsage = new System.Diagnostics.PerformanceCounter();
        cpuUsage.CategoryName = "Processor";
        cpuUsage.CounterName = "% Processor Time";
        cpuUsage.InstanceName = "_Total";


When you test in Visual Studio you will see you can get CPU usage for every call (except first call, it is 0 for the first time). But when you deploy your code to the server probably you will see the error below.
Access to the registry key 'Global' is denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.UnauthorizedAccessException: Access to the registry key 'Global' is denied.
To solve this problem;

1. Check your application pool from the IIS website settings (basic or advance).

2. Go to "Application Pools" section. Right click and select "Advanced Settings".

3. Find "Identity".

4. Go to "Server Manager" > "Local Users and Groups" > "Groups". On the right pane right click to "Performance Monitor Users" > Properties.

5. Add user you saw in the 3rd step (Identity). If you saw "ApplicationPoolIdentity" in the "Identity" then type "IIS APPPool\[Pool name]". In our example pool name is "ASP.NET v4.0".

6. Restart IIS. Now you should see the performance counter page without error.