Remove PictureBox after time

ぃ、小莉子 提交于 2020-01-16 08:41:09

问题


I'm making simple game where I need to remove pictures after certain time without freezing everything else. I'm making explode event:

private void Explode(int x, int y)
{
  PictureBox explosion = new PictureBox();
  explosion.Image = Properties.Resources.explosion;
  explosion.SizeMode = PictureBoxSizeMode.StretchImage;
  explosion.Size = new Size(50, 50);
  explosion.Tag = "explosion";
  explosion.Left = x;
  explosion.Top = y;            
  this.Controls.Add(explosion);
  explosion.BringToFront();
}

I have already one timer for running the game, and i want to use if statement to remove picture when it lasts for 3 sec.

private void timer1_Tick(object sender, EventArgs e)
{
  foreach (Control x in this.Controls) 
  {
    if (x is PictureBox && x.Tag == "explosion")
    {
      if (EXPLOSION LASTS MORE THEN 3sec)
      {
        this.Controls.Remove(x);
      }
    }
  }
}

How can I do this?


回答1:


Assuming you may have multiple picture box at the same time, then instead of using a single timer for multiple picture boxes which may have different explosion timings, you can use async/await and Task.Delay like this:

private async void button1_Click(object sender, EventArgs e)
{
    await AddExplodablePictureBox();
}
private async Task AddExplodablePictureBox()
{
    var p = new PictureBox();
    p.BackColor = Color.Red;
    //Set the Image and other properties
    this.Controls.Add(p);
    await Task.Delay(3000);
    p.Dispose();
}



回答2:


Before removing the picture box, of course it needs to release picturebox resources.

However there is problem when releasing. For more info, you can read more from the link below.

c# picturebox memory releasing problem



来源:https://stackoverflow.com/questions/59569771/remove-picturebox-after-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!