0

Every tick of timer I'd like to check the received data: "000000000" and if any of these bits are set to 1 then change picturebox. This part of code is working - but I think I have a memory leak problem (memory used by program is increasing drastically). How to resolve this problem?

 private void RefreshingTimerTick(object sender, EventArgs e)
 {
    for (int i = 1; i < 9; i++)
    {
       if (ReceivedDataTextBox.Text[i - 1].ToString() == "1")
          ((PictureBox)this.tabPage1.Controls["pictureBox_DO" + i.ToString()]).Image = new Bitmap(@"Logos\\green.png");
       else ((PictureBox)this.tabPage1.Controls["pictureBox_DO" + i.ToString()]).Image = new Bitmap(@"Logos\\red.png");
    }
 }
1
  • 2
    It is not possible for the loop you provided to be an infinite loop. Commented Jun 12, 2012 at 15:56

2 Answers 2

8

You need to dispose of the old image (this.tabPage1.Controls["pictureBox_DO" + i.ToString()]).Image) before assigning it to a new one

private Bitmap _greenBitmap = new Bitmap(@"Logos\green.png"); 
private Bitmap _redBitmap = new Bitmap(@"Logos\red.png");

private void RefreshingTimerTick(object sender, EventArgs e)
{
   for (int i = 1; i < 9; i++)
   {
       PictureBox p = 
          (PictureBox)this.tabPage1.Controls["pictureBox_DO" + i.ToString()];
       if(p != null && p.Image != null)
       {  
          p.Image.Dispose();
       }

       bool is_one = (ReceivedDataTextBox.Text[i - 1].ToString() == "1");
       if(p != null)
       {
          p.Image = (is_one) ? _greenBitmap : _redBitmap;
       }
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

1

Don't create always a new image. Try to pre-create your image and only set it to the control.

private Bitmap greenBitmap = new Bitmap(@"Logos\\green.png"); 
private Bitmap redBitmap = new Bitmap(@"Logos\\red.png")

private void RefreshingTimerTick(object sender, EventArgs e) 
        { 

            for (int i = 1; i < 9; i++) 
            { 
                if (ReceivedDataTextBox.Text[i - 1].ToString() == "1") 
                    ((PictureBox)this.tabPage1.Controls["pictureBox_DO" + i.ToString()]).Image = greenBitmap; 
                else ((PictureBox)this.tabPage1.Controls["pictureBox_DO" + i.ToString()]).Image = redBitmap; 
            } 
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.