65.9K
CodeProject 正在变化。 阅读更多。
Home

使用自定义属性向您的应用程序添加性能计数器

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.54/5 (10投票s)

2006年2月8日

CPOL

2分钟阅读

viewsIcon

81002

downloadIcon

489

简要概述什么是性能计数器,以及一个使它们的使用更容易的库。

引言

性能计数器监视计算机上性能对象的行为。这些包括物理组件,如处理器、磁盘和内存,以及系统对象,如进程和线程。 .NET 公共语言运行时环境也创建(和维护)了大量性能计数器,包括垃圾回收所花费的 % 时间,以及托管堆的总大小等。

The windows preformance monitoring tool

您可以通过运行 perfmon.exe 实用程序来监视系统的行为,该实用程序具有如上所示的界面。您选择您感兴趣的性能计数器,然后将它们绘制成图表。

创建自定义性能计数器

.NET 框架包括两个可用于与性能监视器交互的类:PerformanceCounterCategoryPerformanceCounter - 使用这些,您可以创建自定义性能计数器来监视您自己应用程序的各个方面,以密切关注其性能。

用于性能监视的属性

附带的库包含两个属性派生类,PerformanceCounterCategoryAttributePerformanceCounterAttribute,您可以使用它们来修饰您的业务对象类,然后使用 PerformanceCounterUtilities 类中的共享函数来创建和更新这些性能计数器。

将类与性能计数器类别关联

要将类与特定的性能计数器类别关联,您可以使用 PerformanceCounterCategoryAttribute 属性修饰该类定义。

<PerformanceCounterCategory("Attribute Test", _
"Test of the performance counter utility library")> _
Public Class PerformanceCounterTestClass
'- - 8< - - - - - - - - - - - - - - - - - - -

将类的属性与性能计数器关联

要将类的公共属性与特定的性能计数器关联,您可以使用 PerformanceCounterAttribute 属性修饰该属性定义。

'- - 8< - - - - - - - - - - - - - - - - - - - 
<PerformanceCounter("Value List Length", _
"The number of items in the value list", _ 
PerformanceCounterType.NumberOfItems32)> _
Public ReadOnly Property CurrentList() As Collection
'- - 8< - - - - - - - - - - - - - - - - - - -

PerformanceCounterAttribute 属性具有重载的构造函数,允许您指定性能计数器的类型(如果未明确选择,则假定为 PerformanceCounterType.NumberOfItems32),并且对于那些需要关联基本性能计数器的性能计数器类型(例如,RawFraction 计数器类型需要关联的 Rawbase 计数器类型),您可以指定提供基本性能类别的属性的名称。

(重新)创建性能计数器

在您可以为各种性能计数器分配值之前,您需要创建它们。为此,您将您的类的实例(上面有属性)传递给 RebuildPerformanceCounterCategory。这会创建一个 CounterCreationData 对象集,并将其按正确的顺序放置,以便为该对象类型创建性能计数器。

Private TestClass As New PerformanceCounterTestClass
'\\ Create and register the performance counter categories       
PerformanceCounterUtilities.PerformanceCounterUtilities.
            RebuildPerformanceCounterCategory(TestClass)

从类的实例更新所有性能计数器

要更新与类关联的所有性能计数器,请调用 UpdatePerformanceCounter 方法并传递类实例。

PerformanceCounterUtilities.UpdatePerformanceCounter(TestClass)

从类和属性名称更新单个性能计数器

要更新与类属性关联的单个性能计数器,请调用 UpdatePerformanceCounter 方法并传递类实例和属性名称。

PerformanceCounterUtilities.UpdatePerformanceCounter(TestClass, _
                                                   "Iterations")

使用场景

自定义性能计数器是检测您的 .NET 应用程序以监视性能并诊断该应用程序的任何瓶颈或问题的好方法,并且从长远来看,它们可以节省大量的压力和脱发。

© . All rights reserved.