我一定在这里做错了什么。我创建了一个自定义性能计数器,如下所示:
string counterCategory = "Test Category";
string counterName = "Test Counter";
if (!PerformanceCounterCategory.Exists(counterCategory))
{
Console.WriteLine("Creating Counters");
CounterCreationDataCollection counterCreationDataCollection =
new CounterCreationDataCollection();
counterCreationDataCollection.Add(
new CounterCreationData(counterName,
"Description",
PerformanceCounterType.NumberOfItems32)
);
PerformanceCounterCategory.Create(counterCategory,
"My category description/Help",
PerformanceCounterCategoryType.SingleInstance,
counterCreationDataCollection);
}
计数器类别和计数器在性能监视器中创建和查看。
然后我尝试更改计数器的值
PerformanceCounter myCounter =
new PerformanceCounter(counterCategory, counterName, false);
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Setting to "+i);
myCounter.RawValue = i;
Thread.Sleep(200);
}
myCounter.Close();
然而,当我坐下来观察性能监视器中的计数器时,什么也没发生,值永远不会改变。
那么我做错了什么?
如果我添加对 nextValue() 或 rawValue() 的调用,则该值按预期返回,但 Windows 性能监视器仍显示一条平线,例如
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Setting to "+i);
myCounter.IncrementValue()
Console.WriteLine("Next Value = "+myCounter.RawValue());
Thread.Sleep(200);
}
编辑:我发现如果我关闭性能监视器然后重新打开它而不删除计数器,它会突然意识到有一个新值。因此,这些值正在设置并保持不变,但是性能监视器看不到更改。