要想创建自定义的计数器,先得实现IPerfCounterProvider接口,CreateCounters方法声明要创建的计数器,CountersCreated方法把创建的计数器赋值给本类的成员,PerformanceObjectName返回要创建自定义计数器的分类名。
PerfCounterFactory主要用来创建一个IPerfCounterProvider的实例,它有个GetCounters的泛型方法用来创建一个IPerfCounterProvider的实例,CreateCounters方法用来实际的创建性能计数器,另两个AddPerfCounter方法和Find方法是让IPerfCounterProvider的两个方法用的,下面的例子里会有。
PerfCounter是一个实体类,保存每个计数器的名称,帮助,类型。
好,我们要监控一个web服务的性能,这个Web服务提供相乘和相加的服务,我们要知道这个Web服务的总请求数,每秒调用次数,并发调用数,每个web方法每秒的调用次数,创建计数器如下,关于计数器的类型,及性能计数器的相关内容,请查看MSDN,计数器类型有总量计数器,平均计数器,速率计数器,并发计数器等,分别适用于不同的需求。
复制 保存
public class MathServicePerfCounter : IPerfCounterProvider { static MathServicePerfCounter _instance = PerfCounterFactory.GetCounters<MathServicePerfCounter>(); public static MathServicePerfCounter Instance { get { return _instance; } } public PerformanceCounter TotalOfRequest; public PerformanceCounter RateOfRequest; public PerformanceCounter RateOfAddition; public PerformanceCounter RateOfMultiplication; public PerformanceCounter CountOfCurrentRequest; const string TotalOfRequestStr = "Total # req"; const string RateOfRequestStr = "req/sec"; const string RateOfAdditionStr = "Addition/sec"; const string RateOfMultiplicationStr = "Multiplication/sec"; const string CountOfCurrentRequestStr = "current # req"; #region IPerfCounterProvider 成员 public void CreateCounters() { PerfCounterFactory.AddPerfCounter(new PerfCounter(TotalOfRequestStr, "请求总数", PerformanceCounterType.NumberOfItems64)); PerfCounterFactory.AddPerfCounter(new PerfCounter(RateOfRequestStr, "每秒请求的数量", PerformanceCounterType.RateOfCountsPerSecond64)); PerfCounterFactory.AddPerfCounter(new PerfCounter(RateOfAdditionStr, "每秒相加请求的数量", PerformanceCounterType.RateOfCountsPerSecond64)); PerfCounterFactory.AddPerfCounter(new PerfCounter(RateOfMultiplicationStr, "每秒相成的数量", PerformanceCounterType.RateOfCountsPerSecond64)); PerfCounterFactory.AddPerfCounter(new PerfCounter(CountOfCurrentRequestStr, "当前并发请求量", PerformanceCounterType.RateOfCountsPerSecond64)); } public void CountersCreated() { TotalOfRequest = PerfCounterFactory.Find(TotalOfRequestStr); RateOfRequest = PerfCounterFactory.Find(RateOfRequestStr); RateOfAddition = PerfCounterFactory.Find(RateOfAdditionStr); RateOfMultiplication = PerfCounterFactory.Find(RateOfMultiplicationStr); CountOfCurrentRequest = PerfCounterFactory.Find(CountOfCurrentRequestStr); } public string PerformanceObjectName() { return "MathServicePerfCounter"; } #endregion }
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/