Jes*_*sen 163
您可以使用:
Process proc = Process.GetCurrentProcess();
Run Code Online (Sandbox Code Playgroud)
要获得当前流程并使用:
proc.PrivateMemorySize64;
Run Code Online (Sandbox Code Playgroud)
获取私有内存使用情况.有关更多信息,请查看此链接.
Aus*_*tin 23
System.Environment具有WorkingSet.如果你想要很多细节,那就是System.Diagnostics.PerformanceCounter,但是设置起来会有点费劲.
Ahm*_*yan 12
除了@JesperFyhrKnudsen的回答和@MathiasLykkegaardLorenzen的评论外,您最好在使用后dispose
返回Process
。
因此,为了处置Process
,您可以将其包装在using
范围内或调用Dispose
返回的进程(proc
变量)。
using
范围:
var memory = 0.0;
using (Process proc = Process.GetCurrentProcess())
{
// The proc.PrivateMemorySize64 will returns the private memory usage in byte.
// Would like to Convert it to Megabyte? divide it by 2^20
memory = proc.PrivateMemorySize64 / (1024*1024);
}
Run Code Online (Sandbox Code Playgroud)或Dispose
方法:
var memory = 0.0;
Process proc = Process.GetCurrentProcess();
memory = Math.Round(proc.PrivateMemorySize64 / (1024*1024), 2);
proc.Dispose();
Run Code Online (Sandbox Code Playgroud)现在您可以使用memory
转换为兆字节的变量。
Dev*_*evT 10
看这里了解详情.
private PerformanceCounter cpuCounter;
private PerformanceCounter ramCounter;
public Form1()
{
InitializeComponent();
InitialiseCPUCounter();
InitializeRAMCounter();
updateTimer.Start();
}
private void updateTimer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = "CPU Usage: " +
Convert.ToInt32(cpuCounter.NextValue()).ToString() +
"%";
this.textBox2.Text = Convert.ToInt32(ramCounter.NextValue()).ToString()+"Mb";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void InitialiseCPUCounter()
{
cpuCounter = new PerformanceCounter(
"Processor",
"% Processor Time",
"_Total",
true
);
}
private void InitializeRAMCounter()
{
ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);
}
Run Code Online (Sandbox Code Playgroud)
如果你得到0值,它需要调用NextValue()
两次.然后它给出了CPU使用率的实际值.在这里查看更多细节.