.net 中性能计数器的初始化非常慢

我目前有两个 PerformanceCounter 在我的 Windows 窗体应用程序启动时产生问题。

PerformanceCounter 是在应用程序启动时启动的 UserControl 的设计器类中创建的。创建名为 performanceCounterMemoryperformanceCounterProTime 的计数器能够向用户提供当前使用的 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

zjs0555 回答:.net 中性能计数器的初始化非常慢

long memory = GC.GetTotalMemory(true);

可以使用下面的函数(true参数告诉GC先构建) 这是针对 RAM 的,我不太明白,也许会有所帮助)

本文链接:https://www.f2er.com/3622.html

大家都在问