我有这段代码:我在哪里创建我的性能计数器.它执行正常,如果不存在,它也会创建性能计数器,但是当我使用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);
}
Run Code Online (Sandbox Code Playgroud)
没有收到任何异常的原因是缺少 try-catch 块。如果您像这样在 try 和 catch 块中添加语句
try
{
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);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString()); //Do necessary action
}
Run Code Online (Sandbox Code Playgroud)
然后它将捕获异常。如果您看到类似“不允许请求的注册表访问”的异常。那么你需要管理权限才能做这些事情。要确认这一点,请使用管理权限运行 Visual Studio 并执行代码。