Как получить использование процессора в asp.net - PullRequest
8 голосов
/ 18 марта 2011

Есть ли способ показать статистику использования CPU и RAM на странице asp.net.Я пробовал этот код, но у меня есть ошибка:

Access to the registry key 'Global' is denied.

в этой строке:

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

Ответы [ 4 ]

5 голосов
/ 18 марта 2011

Использование:

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

    float f = cpuUsage.NextValue();

Редактировать:

Windows ограничивает доступ к счетчикам производительности в группах администраторов или пользователей журналов производительности (в Vista +).Настройка безопасности реестра не решит эту проблему.Возможно, к нему где-то прикреплено право пользователя.

5 голосов
/ 18 марта 2011

Как уже упоминалось в комментариях, без соответствующих разрешений вы не сможете это сделать. Статистика ресурсов будет включать в себя много информации о процессах, принадлежащих другим пользователям системы, которая является привилегированной информацией

0 голосов
/ 28 декабря 2016

чтобы не вызывать .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;

        }

    }
}

открытый класс JsonContent: HttpContent { только для чтения 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;
    }
}
0 голосов
/ 16 сентября 2012

Использование:

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

Вместо:

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