15

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();
        }
Jane1990
  • 184
  • 1
  • 1
  • 12

1 Answers1

21

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.
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
Mr Rivero
  • 1,248
  • 7
  • 17
  • Thanks you correct :) I dont know why I didnt saw that as well lol too long on my desk, need break. Thanks anyway – Jane1990 Apr 19 '15 at 00:25
  • Must include assembly `Microsoft.VisualBasic`, in order to see `ComputerInfo`. – Contango May 06 '17 at 11:37
  • `ComputerInfo` found in `Microsoft.VisualBasic.Devices` namespace – Matt Nelson Aug 30 '17 at 19:59
  • In the following post, the proposed answer suggest using the PerformanceCounter class, from the System.Diagnostics namespace(it also retrieves the cpu usage). https://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c – Sotiris Zegiannis Oct 06 '22 at 17:22