【发布时间】:2021-10-06 22:14:21
【问题描述】:
我目前有两个 PerformanceCounters 在我的 Windows 窗体应用程序启动时产生问题。
PerformanceCounters 是在应用程序启动时启动的UserControl 的设计器类中创建的。创建称为performanceCounterMemory 和performanceCounterProTime 的计数器能够为用户提供当前使用的RAM 内存和处理时间(百分比)的实时反馈。它们是在设计器类中使用以下行创建的
this.performanceCounterMemory = new System.Diagnostics.PerformanceCounter();
this.performanceCounterProTime = new System.Diagnostics.PerformanceCounter();
((System.ComponentModel.ISupportInitialize)(this.performanceCounterMemory)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.performanceCounterProTime)).BeginInit();
this.performanceCounterMemory.CategoryName = "Memory";
this.performanceCounterMemory.CounterName = "% used dedicated byte";
this.performanceCounterProTime.CategoryName = "Processor";
this.performanceCounterProTime.CounterName = "% Processor Time";
this.performanceCounterProTime.InstanceName = "_Total";
((System.ComponentModel.ISupportInitialize)(this.performanceCounterMemory)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.performanceCounterProTime)).EndInit();
由于未知原因,对最后两行的调用,EndInit() 调用,因为两个计数器都非常慢(10 多秒),导致应用程序启动非常慢。
这是为什么? EndInit 调用的目的是什么?是否可以让它更快?
为了能够使用计数器,以下两个引用由行添加
using System.Management.Instrumentation;
using System.Management;
机器处理器是:Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
【问题讨论】:
-
我相信 EndInit 基本上就像
Wait一样,等待初始化完成。它很慢。您可以将其移至另一个线程或等待调用 EndInit 直到您准备好读取计数器 -
我明白了,感谢您指出这一点。知道为什么与
DataGridView等其他控件相比,性能计数器的初始化时间要长得多吗? -
我真的没有,但我注意到了。我知道它们必须运行一段时间才能获得有意义的数据(随时间对 CPU 使用情况进行采样)。
-
确实,但是我希望应用程序能够检测到某个时间段内任一计数器的值是否/何时超过某个值。
-
不要使用 PerformanceCounter 组件,运行 PerformanceCounter 类对象并从 ThreadPool 线程返回它们的值。阅读有关多线程的说明。
标签: c# .net windows winforms performancecounter