2011-10-03 74 views
7

您好我正在嘗試創建一個自定義性能計數器在perfmon中使用。下面的代碼工作得很好,但我有一個問題..但我有一個問題..在c#中的自定義性能計數器/ perfmon

有了這個解決方案,我有一個計時器更新性能計數器的值,但我想不必運行此可執行文件來獲取我需要的數據。這就是我希望能夠將計數器安裝爲一次性事件,然後對數據進行perfmon查詢(與所有預先安裝的計數器一樣)。

我該如何做到這一點?

using System; 
using System.Diagnostics; 
using System.Net.NetworkInformation; 

namespace PerfCounter 
{ 
class PerfCounter 
{ 
    private const String categoryName = "Custom category"; 
    private const String counterName = "Total bytes received"; 
    private const String categoryHelp = "A category for custom performance counters"; 
    private const String counterHelp = "Total bytes received on network interface"; 
    private const String lanName = "Local Area Connection"; // change this to match your network connection 
    private const int sampleRateInMillis = 1000; 
    private const int numberofSamples = 100; 

    private static NetworkInterface lan = null; 
    private static PerformanceCounter perfCounter; 

    static void Main(string[] args) 
    { 
     setupLAN(); 
     setupCategory(); 
     createCounters(); 
     updatePerfCounters(); 
    } 

    private static void setupCategory() 
    { 
     if (!PerformanceCounterCategory.Exists(categoryName)) 
     { 
      CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection(); 
      CounterCreationData totalBytesReceived = new CounterCreationData(); 
      totalBytesReceived.CounterType = PerformanceCounterType.NumberOfItems64; 
      totalBytesReceived.CounterName = counterName; 
      counterCreationDataCollection.Add(totalBytesReceived); 
      PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection); 
     } 
     else 
      Console.WriteLine("Category {0} exists", categoryName); 
    } 

    private static void createCounters() { 
     perfCounter = new PerformanceCounter(categoryName, counterName, false); 
     perfCounter.RawValue = getTotalBytesReceived(); 
    } 

    private static long getTotalBytesReceived() 
    { 
     return lan.GetIPv4Statistics().BytesReceived; 
    } 

    private static void setupLAN() 
    { 
     NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); 
     foreach (NetworkInterface networkInterface in interfaces) 
     { 
      if (networkInterface.Name.Equals(lanName)) 
       lan = networkInterface; 
     } 
    } 
    private static void updatePerfCounters() 
    { 
     for (int i = 0; i < numberofSamples; i++) 
     { 
      perfCounter.RawValue = getTotalBytesReceived(); 
      Console.WriteLine("perfCounter.RawValue = {0}", perfCounter.RawValue); 
      System.Threading.Thread.Sleep(sampleRateInMillis); 
     } 
    } 
} 

}

回答

6

在Win32中,性能計數器由具有性能監視器加載DLL,其提供的計數器值工作。

在.NET中,此DLL是一個存根,它使用共享內存與正在運行的.NET進程進行通信。該進程週期性地將新值推送到共享內存塊,並且該DLL使它們作爲性能計數器可用。

因此,基本上,您可能必須在本地代碼中實現性能計數器DLL,因爲.NET性能計數器假定有一個進程正在運行。

相關問題