创建位图时可能的内存泄漏

时间:2012-06-12 15:53:02

标签: c# winforms

计时器的每个滴答我想检查收到的数据:"000000000",如果这些位中的任何一个设置为1,则更改图片框。这部分代码正在运行 - 但我认为我有内存泄漏问题(程序使用的内存正在急剧增加)。如何解决这个问题?

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

2 个答案:

答案 0 :(得分:8)

您需要在将旧图像(this.tabPage1.Controls["pictureBox_DO" + i.ToString()]).Image)分配给新图像之前将其丢弃

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

答案 1 :(得分:1)

不要始终创建新图像。 尝试预先创建图像,只将其设置为控件。

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