[英]How to get memory available or used in C#
How can I get the available RAM or memory used by the application?如何获取应用程序使用的可用 RAM 或 memory?
You might want to check the GC.GetTotalMemory method.您可能想要检查GC.GetTotalMemory方法。
It retrieves the number of bytes currently thought to be allocated by the garbage collector.它检索当前认为由垃圾收集器分配的字节数。
System.Environment has WorkingSet - a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context. System.Environment具有WorkingSet - 一个 64 位有符号整数,包含映射到进程上下文的物理内存的字节数。
If you want a lot of details there is System.Diagnostics.PerformanceCounter , but it will be a bit more effort to setup.如果您想要很多细节,可以使用System.Diagnostics.PerformanceCounter ,但设置起来会更费力。
In addition to @JesperFyhrKnudsen 's answer and @MathiasLykkegaardLorenzen 's comment, you'd better dispose
the returned Process
after using it.除了@JesperFyhrKnudsen的回答和@MathiasLykkegaardLorenzen的评论外,您最好在使用后
dispose
返回的Process
。
So, In order to dispose the Process
, you could wrap it in a using
scope or calling Dispose
on the returned process ( proc
variable).因此,为了处置
Process
,您可以将其包装在using
范围内或在返回的进程( proc
变量)上调用Dispose
。
using
scope: 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); }
Or Dispose
method:或
Dispose
方法:
var memory = 0.0; Process proc = Process.GetCurrentProcess(); memory = Math.Round(proc.PrivateMemorySize64 / (1024*1024), 2); proc.Dispose();
Now you could use the memory
variable which is converted to Megabyte.现在您可以使用转换为兆字节的
memory
变量。
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);
}
If you get value as 0 it need to call NextValue()
twice.如果您获得的值为 0,则需要调用
NextValue()
两次。 Then it gives the actual value of CPU usage.然后它给出了 CPU 使用率的实际值。 See more details here .
在此处查看更多详细信息。
For the complete system you can add the Microsoft.VisualBasic Framework as a reference;对于完整的系统,您可以添加 Microsoft.VisualBasic Framework 作为参考;
Console.WriteLine("You have {0} bytes of RAM",
new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
Console.ReadLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.