【发布时间】:2012-07-17 18:41:19
【问题描述】:
我有这段代码: 我在哪里创建我的性能计数器。它执行正常,如果不存在,它也会创建性能计数器,但是当我使用 perfmon 时,我找不到这个性能计数器。
发生了什么?
const string _categoryName = "MyPerformanceCounter";
if (!PerformanceCounterCategory.Exists(_categoryName))
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
CounterCreationData ccdWorkingThreads = new CounterCreationData();
ccdWorkingThreads.CounterName = "# working threads";
ccdWorkingThreads.CounterHelp = "Total number of operations executed";
ccdWorkingThreads.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(ccdWorkingThreads);
// create new category with the counters above
PerformanceCounterCategory.Create(_categoryName,
"Performance counters of my app",
PerformanceCounterCategoryType.SingleInstance,
counters);
}
【问题讨论】:
-
过去我在使用性能计数器时遇到的一个问题是,正在运行的进程必须是管理员,或者具有创建性能计数器的特定权限。这就是为什么通常在安装时而不是运行时创建新的性能计数器的原因。我不记得如果您的应用程序没有管理员权限会发生什么;它可能只是默默地无法创建计数器。虽然我认为它会引发异常......但无论如何,如果您还没有,请尝试以管理员身份运行您的应用程序。
-
另外,如果您在 perfmon 运行时创建计数器,则需要重新启动 perfmon 以使其识别新的计数器。
-
另外,计数器不会立即可见。有时需要几秒钟才能看到它们。
-
所以,
PerformanceCounterCategory.Create()可以什么都不做,不抛出异常。 -
我刚刚在 Windows 7 上运行了您的代码,并且该类别已按预期创建。而且您并没有真正创建PerformanceCounter,您只是在定义一个PerformanceCounterCategory。尝试创建一个 PerformanceCounter 来确定是否引发了异常。