有没有办法在asp.net页面上显示CPU和RAM使用情况统计信息。我已经尝试了this代码,但我有错误:
Access to the registry key 'Global' is denied.
在这一行:
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
答案 0 :(得分:5)
如评论中所述,如果没有相应的权限,您将无法执行此操作。资源统计信息将包含大量有关系统其他用户拥有的进程的信息,这些信息是特权信息
答案 1 :(得分: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 +中)组中的访问权限。设置注册表安全性无法解决此问题。有可能在某处附加了用户权限。
答案 2 :(得分: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 { 私人只读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;
}
}
答案 3 :(得分:-3)
使用:
new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
而不是:
new PerformanceCounter("Processor", "% Processor Time", "_Total");