gpt4 book ai didi

c# - 如何在不让用户在命令提示符下使用 lodctr 重建的情况下让性能计数器工作?

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

我一直在尝试在 C# 中获取 Windows PC(运行 .Net 4.5 的 Windows 7)的总 CPU 使用率。看来使用PerformanceCounter应该可以满足我的需求。

我根据下面的三个链接写了一些试用代码(并检查了 msdn 页面),这是最基本的版本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace EntropyProject
{
class Program
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;

cpuCounter = new PerformanceCounter();

cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";


while(true)
{
try
{
float firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(500);
Console.WriteLine("Before getting processor:");
float currentCpuUsage = cpuCounter.NextValue();
Console.WriteLine("After getting processor:");
System.Threading.Thread.Sleep(1000);

Console.WriteLine(currentCpuUsage);
}
catch (Exception e)
{
Console.WriteLine("\n{0}\n", e.Message);
}
System.Threading.Thread.Sleep(10000);

}
}
}
}

每当调用 NextValue 时,都会触发以下异常错误。这似乎是性能计数器值问题的常见问题。

Cannot load Counter Name data because an invalid index '' was read from registry

最推荐solutions建议您以管理员身份在弹出的命令窗口中使用 lodctr 重建损坏的项目。但是,我想在一个将发布给大量用户的程序中使用 PerformanceCounters,因此期望他们使用命令窗口重建他们的 PerformanceCounters 是不合适的。

问题:

  1. 为什么会出现这个异常错误?
  2. 您如何正确使用 PerformanceCounter?
  3. 如何避免让我的程序用户不得不打开 cmd 窗口并重建他们的性能计数器?

来源:

  1. How to get cpu usage in C

  2. Get current cpu utilisation in

  3. How can I get the total CPU usage?

Similar Question about error when accessing counter name Annie Sheikh 问

最佳答案

根据 PerformanceCounter.NextValue 的文档,“要读取性能计数器,您必须具有管理权限。”文档还指出,如果“在没有管理权限的情况下执行的代码试图读取性能计数器,则会抛出 UnauthorizedAccessException。

但这是一个谎言。在我的 Windows 7 环境(64 位家庭高级版)上,运行 .NET 4.5,我可以在管理员帐户、标准用户帐户甚至 guest 帐户上从非启动的 cmd shell 运行您的代码。

如果您遇到权限问题,那么很可能再多的注册表修改都无法让您的代码为所有用户可靠地运行。但我不清楚为什么您的代码在没有管理员权限的 guest 帐户上运行良好,根据文档说明。

另一种选择是运行“wmic.exe cpu get loadpercentage”并解析输出,如this answer 中所建议的那样.根据我的测试,这适用于管理员或标准用户帐户,但不适用于 guest 帐户。

关于c# - 如何在不让用户在命令提示符下使用 lodctr 重建的情况下让性能计数器工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28286527/

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