如何在asp.net中获取CPU使用率

12

有没有一种方法可以在一个ASP.NET页面上显示CPU和RAM使用统计信息。我尝试过这段代码但出现了错误:

Access to the registry key 'Global' is denied.

在这一行上:

ramCounter = new PerformanceCounter("Memory", "Available MBytes");

1
你尝试过使用Process类吗?例如Process.GetCurrentProcess()Process.TotalProcessorTime?通过测量该值在固定时间内的增长量,您可以轻松地计算出在该时间段内您所获得/使用的CPU百分比。我将其留作评论,因为我不知道您是否被允许检查给出的错误消息。 - Lasse V. Karlsen
你有访问IIS管理的权限吗?如果有,那么你可以授予你的工作进程池访问注册表的权限。如果没有 - 例如,如果你使用的是共享主机 - 那么很抱歉,你就无法访问了。 - Stuart
@Stuard:我有自己运行Windows Server 2008的VDS。可能最好的解决方案是编写一个Windows服务。 - HasanG
4个回答

5

使用:

    System.Diagnostics.PerformanceCounter cpuUsage = 
      new System.Diagnostics.PerformanceCounter();
    cpuUsage.CategoryName = "Processor"; 
    cpuUsage.CounterName = "% Processor Time";
    cpuUsage.InstanceName = "_Total";

    float f = cpuUsage.NextValue();

编辑:

Windows将性能计数器的访问权限限制为管理员或性能日志用户组(在Vista+中)。设置注册表安全性不会解决此问题。可能有一个与之相关联的用户权限。


你需要运行 cupUsage.NextValue() 两次...第一次调用总是会返回0,第二次调用将返回自上次调用以来的平均CPU使用率。 - saluce

5

如评论中所述,如果没有适当的权限,您将无法执行此操作。资源统计信息将包括许多关于系统其他用户拥有的进程的信息,这是特权信息。


我相信你是正确的...但是你能否提供更多信息...假设你自己遇到过这个问题,知道需要什么权限和不需要什么权限.. - Seabizkit

0

为了避免调用两次.NextValue(),您可以使用MVC“全局变量”:

    [AllowAnonymous]
    [HttpGet]
    [ActionName("serverusage")]
    public HttpResponseMessage serverusage()
    {
        try
        {

            PerformanceCounter cpuCounter;

            if (HttpContext.Current.Application["cpuobj"] == null)
            {
                cpuCounter = new PerformanceCounter();
                cpuCounter.CategoryName = "Processor";
                cpuCounter.CounterName = "% Processor Time";
                cpuCounter.InstanceName = "_Total";

                HttpContext.Current.Application["cpuobj"] = cpuCounter;
            }
            else
            {
                cpuCounter = HttpContext.Current.Application["cpuobj"] as PerformanceCounter;
            }

            JToken json;
            try
            {
                json = JObject.Parse("{ 'usage' : '" + HttpContext.Current.Application["cpu"] + "'}");
            }
            catch
            {
                json = JObject.Parse("{ 'usage' : '" + 0 + "'}");
            }

                HttpContext.Current.Application["cpu"] = cpuCounter.NextValue();

            var response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
            response.Content = new JsonContent(json);
            return response;

        }
        catch (Exception e)
        {
            var response = Request.CreateResponse(System.Net.HttpStatusCode.BadRequest);
            JToken json = JObject.Parse("{ 'problem' : '" + e.Message + "'}");
            response.Content = new JsonContent(json);
            return response;

        }

    }
}

public class JsonContent : HttpContent { private readonly JToken _value;

公共类JsonContent:HttpContent { private readonly JToken _value; }
    public JsonContent(JToken value)
    {
        _value = value;
        Headers.ContentType = new MediaTypeHeaderValue("application/json");
    }

    protected override Task SerializeToStreamAsync(Stream stream,
        TransportContext context)
    {
        var jw = new JsonTextWriter(new StreamWriter(stream))
        {
            Formatting = Formatting.Indented
        };
        _value.WriteTo(jw);
        jw.Flush();
        return Task.FromResult<object>(null);
    }

    protected override bool TryComputeLength(out long length)
    {
        length = -1;
        return false;
    }
}

-2

使用:

new PerformanceCounter("Processor Information", "% Processor Time", "_Total");

改为:

new PerformanceCounter("Processor", "% Processor Time", "_Total");

1
为什么OP应该这样做?请解释! - markus
这并没有真正帮助。但是,它提供了信息,如果主板上有多个物理处理器(CPU)和多个可能是超线程的核心。实例名称被给定为0,0,表示第一个CPU上的第一个核心,或者1,_Total表示第二个CPU的平均值,以及_Total表示整个CPU集群。它提供了更多关于物理处理能力的信息,但它并没有提供任何有助于原始问题的东西。 - saluce
这两个解决方案中的任何一个如何解决“拒绝访问注册表项'Global'”的问题? - Seabizkit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接