有没有一种方法可以在一个ASP.NET页面上显示CPU和RAM使用统计信息。我尝试过这段代码但出现了错误:
Access to the registry key 'Global' is denied.
在这一行上:
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
有没有一种方法可以在一个ASP.NET页面上显示CPU和RAM使用统计信息。我尝试过这段代码但出现了错误:
Access to the registry key 'Global' is denied.
在这一行上:
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
使用:
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如评论中所述,如果没有适当的权限,您将无法执行此操作。资源统计信息将包括许多关于系统其他用户拥有的进程的信息,这是特权信息。
为了避免调用两次.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;
}
}
使用:
new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
改为:
new PerformanceCounter("Processor", "% Processor Time", "_Total");
0,0
,表示第一个CPU上的第一个核心,或者1,_Total
表示第二个CPU的平均值,以及_Total
表示整个CPU集群。它提供了更多关于物理处理能力的信息,但它并没有提供任何有助于原始问题的东西。 - saluce
Process.GetCurrentProcess()
和Process.TotalProcessorTime
?通过测量该值在固定时间内的增长量,您可以轻松地计算出在该时间段内您所获得/使用的CPU百分比。我将其留作评论,因为我不知道您是否被允许检查给出的错误消息。 - Lasse V. Karlsen