如何在C#中获取或使用内存

126 c# memory-management

如何获取应用程序使用的可用RAM或内存?

Jes*_*sen 163

您可以使用:

Process proc = Process.GetCurrentProcess();
Run Code Online (Sandbox Code Playgroud)

要获得当前流程并使用:

proc.PrivateMemorySize64;
Run Code Online (Sandbox Code Playgroud)

获取私有内存使用情况.有关更多信息,请查看此链接.

  • 应该注意的是,对GetCurrentProcess的调用本身会分配相当多的资源.完成后调用返回的进程,或将整个代码包装在"使用"范围内. (48认同)
  • 我还想补充一点,在调用Refresh()之前,PrivateMemorySize64属性(+其他属性)本身不会自动更新.(它在上面链接的页面上提到过.) (9认同)
  • 命名空间:System.Diagnostics程序集:系统(在System.dll中) (7认同)

CMS*_*CMS 37

您可能想要检查GC.GetTotalMemory方法.

它检索当前认为由垃圾收集器分配的字节数.

  • 只是在管理堆中.Arkain的答案应该给出本机和管理堆. (11认同)

Aus*_*tin 23

System.Environment具有WorkingSet.如果你想要很多细节,那就是System.Diagnostics.PerformanceCounter,但是设置起来会有点费劲.


Ahm*_*yan 12

除了@JesperFyhrKnudsen的回答和@MathiasLykkegaardLorenzen的评论外,您最好在使用后dispose返回Process

因此,为了处置Process,您可以将其包装在using范围内或调用Dispose返回的进程(proc变量)。

  1. 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)
  2. 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转换为兆字节的变量。

  • 注意:1MB 是 2^20 不是 1e+6 (3认同)
  • 一张纸条。在 C# 中,“^”是按位异或,而不是幂。因此只需使用 `proc.PrivateMemorySize64 / (1024*1024)` 或 `proc.PrivateMemorySize64 / (1 << 20)` (2认同)

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使用率的实际值.在这里查看更多细节.