Jane1990
Jane1990

Reputation: 184

Get Available Free RAM Memory C#

Need perform free available memory every 1sec, so I use method and timer tick, but it is not changing, it shows always 8081MB in the label text. So how to make it to it check every 1sec? Because using computer memory change also. Here is my code:

    // Get Available Memory 
        public void getAvailableRAM()
        {
            ComputerInfo CI = new ComputerInfo();
            ulong mem = ulong.Parse(CI.TotalPhysicalMemory.ToString());
            lbl_Avilable_Memory.Text = (mem / (1024 * 1024) + " MB").ToString();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            // Get Available Memory Timer 

            ram_timer.Enabled = true;

            // end memory 

        }
        private void ram_timer_Tick(object sender, EventArgs e)
        {
            getAvailableRAM();
        }

Upvotes: 15

Views: 17584

Answers (1)

Mr Rivero
Mr Rivero

Reputation: 1248

Try with this...

Include a reference to the Microsoft.VisualBasic dll:

using Microsoft.VisualBasic.Devices;

...and then update your label as follows:

lbl_Avilable_Memory.Text = new ComputerInfo().AvailablePhysicalMemory.ToString() + " bytes free";

...or...

lbl_Avilable_Memory.Text = (ComputerInfo().AvailablePhysicalMemory / 1048576) + "mb free";

Notes:

  1. Reference the AvailablePhysicalMemory property of the ComputerInfo class in preference over the TotalPhysicalMemory property you used previously.
  2. The getAvailableRAM() method isn't required. Replace the call in ram_timer_tick with lbl_Avilable_Memory.Text = (ComputerInfo().AvailablePhysicalMemory / 1048576) + "mb free";
  3. It's also worth considering that methods that begin with the word get are expected to return a value. If the method was to stay then I'd recommend renaming it to SetLbl_Avilable_Memory() instead.
  4. You have spelled the word available incorrectly in your label name.

Upvotes: 21

Related Questions