问题
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