I'm trying to read the CPU and Memory usage for my app using PerformanceCounters.
code:
PerformanceCounter cpuCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
var result = cpuCounter.NextValue();//ERROR HERE
I'm getting a Unauthorized exception. How can I work around this?
Edit 1:
I tried to set the current instance name for both the processor count and the memory without luck...
Edit 2:
the exception .ToString() is
System.UnauthorizedAccessException: Access to the registry key 'Global' is denied. at Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str) at Microsoft.Win32.RegistryKey.InternalGetValue(String name, Object defaultValue, Boolean doNotExpand, Boolean checkSecurity) at Microsoft.Win32.RegistryKey.GetValue(String name) at System.Diagnostics.PerformanceMonitor.GetData(String item) at System.Diagnostics.PerformanceCounterLib.GetPerformanceData(String item) at System.Diagnostics.PerformanceCounterLib.get_CategoryTable() at System.Diagnostics.PerformanceCounterLib.CounterExists(String category, String counter, Boolean& categoryExists) at System.Diagnostics.PerformanceCounterLib.CounterExists(String machine, String category, String counter) at System.Diagnostics.PerformanceCounter.InitializeImpl() at System.Diagnostics.PerformanceCounter.Initialize() at System.Diagnostics.PerformanceCounter.NextSample() at System.Diagnostics.PerformanceCounter.NextValue() at StudioTech.Web.Infrastructure.CustomMachineMonitoring.<>c__DisplayClass0_0.<b__0>d.MoveNext() in C:\MMT\One\StudioTech.Web\Infrastructure\CustomMachineMonitoring.cs:line 33
According to the exception information, it indicates that we have no access to Performance Monitor. As WebApp is a sandbox, if we use the Azure WebApp, we have no access to do that.
My suggestion is that we could use Application Insight to do that. We need to configurate Application Insight for WebApp, more details please refer to the document. About Performance Counters in the Application Insight, we could refer to this tutorials.
If we try to use Application Insight API, we need to create a Apikey. We also could get demo code from the document. It works correctly for me.