建立自定義的Performance Counter

  • 325
  • 0
  • 2017-04-03

1. 註冊Performance Counter

2. 撰寫Performance Counter的程式

在.NET中要使用Performance Counter可以使用System.Diagnostics.PerformanceCounter,

使用方式並不難,可以使用 Increment、IncrementBy、RawValue等方法進行記錄,

不過,使用前需要先做註冊的動作。

 

要註冊PerformanceCounter需要先定義PerformanceCounterCategory、

然後定義CounterName、CounterType,

這段程式需要較高的權限才能執行,

        if ( !PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") ) 
        {

            CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData averageCount64 = new CounterCreationData();
            averageCount64.CounterType = PerformanceCounterType.AverageCount64;
            averageCount64.CounterName = "AverageCounter64Sample";
            counterDataCollection.Add(averageCount64);

            // Add the base counter.
            CounterCreationData averageCount64Base = new CounterCreationData();
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
            averageCount64Base.CounterName = "AverageCounter64SampleBase";
            counterDataCollection.Add(averageCount64Base);

            // Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance counter type.",
                PerformanceCounterCategoryType.SingleInstance, counterDataCollection);

            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - AverageCounter64SampleCategory");
            return(false);
        }

 

接下來使用Performance Counter的程式碼就只需要短短幾行即可完成,

首先,先建立起Counter物件,並且初始化

        avgCounter64Sample = new PerformanceCounter("AverageCounter64SampleCategory", 
            "AverageCounter64Sample", 
            false);


        avgCounter64SampleBase = new PerformanceCounter("AverageCounter64SampleCategory", 
            "AverageCounter64SampleBase", 
            false);

        avgCounter64Sample.RawValue=0;
        avgCounter64SampleBase.RawValue=0;

再來,在計數的位置以IncrementBy、Increment…等方法進行計數

            avgCounter64Sample.IncrementBy(value);

            avgCounter64SampleBase.Increment();

這樣就完成了。

 

使用方法和EventLog基本上是一樣的,只是MSDN的寫法一直都看不太懂,最近才弄清楚,

寫篇文章記錄下來。

 

參考網址:https://msdn.microsoft.com/zh-tw/library/system.diagnostics.performancecounter(v=vs.110).aspx