2015-10-05 20 views
1

我想在應用程序中使用.NET性能計數器。這裏是代碼:使用.net性能計數器時崩潰

if (!PerformanceCounterCategory.Exists("Processor")) 
{ 
    CounterCreationDataCollection CCDC = new CounterCreationDataCollection(); 

    // Add the counter. 
    CounterCreationData NOI64 = new CounterCreationData(); 
    NOI64.CounterType = PerformanceCounterType.NumberOfItems64; 
    NOI64.CounterName = "%Processor Time"; 
    CCDC.Add(NOI64); 

    // Create the category. 
    PerformanceCounterCategory.Create("Processor", "", PerformanceCounterCategoryType.SingleInstance, CCDC); 
} 
PerformanceCounter PC = new PerformanceCounter("Processor", "%Processor Time", false); 
PC.RawValue = 0; 

當我執行這個代碼,我在下面

提到的類型的未處理的異常PerformanceCounter PC = new PerformanceCounter("Processor", "%Processor Time", false);得到崩潰 'System.InvalidOperationException' 發生在System.dll中

附加信息:請求的性能計數器不是自定義計數器,它必須初始化爲ReadOnly。

我試圖using lodctr命令也不過它在The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly

回答

1

提到的力工作,讓你有什麼實現?它清楚地表明,您應該將其初始化爲只讀。因此,根據documentation,您需要通過true而不是false作爲第三個參數。

此外,不要將零分配給RawValue屬性。這不會起作用(因爲計數器是隻讀的)。

+0

awww ...我真的忽略了這個參數,並且在設置性能計數器方面做了很多故障排除。謝謝你的幫助... – Nipun