gpt4 book ai didi

c# - c#/perfmon 中的自定义性能计数器

转载 作者:太空狗 更新时间:2023-10-29 20:25:18 26 4
gpt4 key购买 nike

您好,我正在尝试创建一个用于 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);
}
}
}

最佳答案

在 Win32 中,性能计数器通过让 PerfMon 加载提供计数器值的 DLL 来工作。

在 .NET 中,此 DLL 是一个 stub ,它使用共享内存与正在运行的 .NET 进程进行通信。该进程定期将新值推送到共享内存块,DLL 使它们可用作性能计数器。

因此,基本上,您可能必须在 native 代码中实现性能计数器 DLL,因为 .NET 性能计数器假定有一个进程正在运行。

关于c# - c#/perfmon 中的自定义性能计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7633985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com