首页 文章

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

提问于
浏览
118

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

6 回答

  • 21

    您可以使用:

    Process proc = Process.GetCurrentProcess();
    

    要获得当前流程并使用:

    proc.PrivateMemorySize64;
    

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

  • 1

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

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

  • 0

    System.EnvironmentWorkingSet . 如果你想要很多细节,那么System.Diagnostics.PerformanceCounter,但设置会更加努力 .

  • 7

    请查看here了解详情 .

    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);
    
    }
    

    如果您将值设为0,则需要两次调用 NextValue() . 然后它给出了CPU使用率的实际值 . 查看更多详情here .

  • 34

    除了@JesperFyhrKnudsen的答案和@MathiasLykkegaardLorenzen 's comment, you' d更好 dispose 使用后返回 Process .

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

    • 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 1e+6
           memory = proc.PrivateMemorySize64 / 1e+6;
    }
    
    • Dispose 方法:
    var memory = 0.0;
    Process proc = Process.GetCurrentProcess();
    memory = Math.Round(proc.PrivateMemorySize64 / 1e+6, 2);
    proc.Dispose();
    

    现在您可以使用转换为兆字节的 memory 变量 .

  • 153

    对于完整的系统,您可以添加Microsoft.VisualBasic Framework作为参考;

    Console.WriteLine("You have {0} bytes of RAM",
            new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
            Console.ReadLine();
    

相关问题