[英]Memory PerformanceCounter C#
我在 C# 中遇到了 PerformanceCounter 的问题。当我在远程机器上运行它时它运行良好,但是当我试图在它运行的机器上运行它时我得到以下错误: System.InvalidOperationException:'Could not locate Performance具有指定类别名称“内存”、计数器名称“% Committed Bytes In Use”的计数器。
int i = 1;
PerformanceCounter ramPerfCounter = new PerformanceCounter();
ramPerfCounter.CategoryName = "Memory";
ramPerfCounter.CounterName = "% Committed Bytes In Use";
ramPerfCounter.MachineName = "server";
ramPerfCounter.ReadOnly = true;
PerformanceCounter cpuPerfCounter = new PerformanceCounter();
cpuPerfCounter.CategoryName = "Processor";
cpuPerfCounter.CounterName = "% Processor Time";
cpuPerfCounter.InstanceName = "_Total";
cpuPerfCounter.MachineName = "server";
cpuPerfCounter.ReadOnly = true;
do
{
float fMemory = ramPerfCounter.NextValue();
float fCpu = cpuPerfCounter.NextValue();
Console.WriteLine("CPU: " + fCpu.ToString());
Console.WriteLine("RAM:" + fMemory.ToString());
Thread.Sleep(1000);
}
while (i == 1);
CPU 性能计数器工作正常。
可能是几个问题
检查您的机器上的计数器是否可用
或者,您可以使用此代码获取类别列表
public static List<string> GetCategoryNames(string machineName)
{
List<string> catNameList = new List<string>();
List<PerformanceCounterCategory> categories = new List<PerformanceCounterCategory>();
try
{
if (!string.IsNullOrEmpty(machineName))
{
categories = PerformanceCounterCategory.GetCategories(machineName).ToList();
}
else
{
categories = PerformanceCounterCategory.GetCategories().ToList();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
foreach(PerformanceCounterCategory category in categories)
{
catNameList.Add(category.CategoryName);
}
catNameList.Sort();
return catNameList;
}
然后添加 catNameList.Contains() 调用以检查计数器是否可用。
找到您可以使用的所有计数器
public static Dictionary<string, List<string>> GetPerfCounterNames(string machineName)
{
Dictionary<string, List<string>> perfCounterList = new Dictionary<string, List<string>>();
List<PerformanceCounterCategory> categories = new List<PerformanceCounterCategory>();
try
{
if (!string.IsNullOrEmpty(machineName))
{
categories = PerformanceCounterCategory.GetCategories(machineName).ToList();
}
else
{
categories = PerformanceCounterCategory.GetCategories().ToList();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
foreach (PerformanceCounterCategory category in categories)
{
List<PerformanceCounter> pcList = null;
if (category.GetInstanceNames().Length > 0)
{
pcList = category.GetCounters(category.GetInstanceNames()[0]).ToList();
}
else
{
pcList = category.GetCounters().ToList();
}
List<string> pcNameList = new List<string>();
foreach (PerformanceCounter pc in pcList)
{
pcNameList.Add(pc.CounterName);
}
pcNameList.Sort();
perfCounterList.Add(category.CategoryName, pcNameList);
}
return perfCounterList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.