我在C#的PerformanceCounter考试上遇到了麻烦。当我在远程机器上运行它时,它运行得很好,但是当试图在运行它的机器上运行它时,我会得到以下错误:System.InvalidOperationException:‘无法找到具有指定类别名称'Memory’的性能计数器,计数器名称'% Committed在使用‘’。
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性能计数器工作得很好。
发布于 2020-10-26 21:32:01
可能是几个问题
检查您的计算机上是否有计数器可用
“监视工具”性能监视器面板上的资源管理器counter
或者,您可以使用此代码获取类别列表。
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;
}https://stackoverflow.com/questions/64545080
复制相似问题