0

计时器的每一个滴答声我都想检查接收到的数据:"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");
    }
 }
4

2 回答 2

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;
       }
    }
 }
于 2012-06-12T15:54:30.280 回答
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; 
            } 
        }
于 2012-06-12T15:55:46.910 回答