Basic sample code of managing a dynamic collection of items
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private List<Bullet> Bullets;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Bullets = new List<Bullet>();
timerControls.Interval = 500;
timerControls.Start();
timerBullets.Interval = 100;
timerBullets.Start();
}
private void timerBullets_Tick(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessBullets));
t.Start();
}
private void ProcessBullets()
{
foreach (var b in Bullets)
{
b.Update();
}
var deadBullets = Bullets.Where(b => b.Destroy).ToList();
if (deadBullets.Count == 0)
{
return;
}
deadBullets.First().BulletUI.Invoke((MethodInvoker)delegate { deadBullets.ForEach(b => this.Controls.Remove(b.BulletUI)); });
Bullets.RemoveAll(b => b.Destroy);
}
private void timerControls_Tick(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine(System.Threading.Thread.CurrentThread.GetHashCode());
Bullet b = new Bullet();
b.Location = new Point(10, 200);
b.Speed = 10;
Label lbl = new Label { Text = "X", Left = b.Location.X, Top = b.Location.Y };
b.BulletUI = lbl;
this.Controls.Add(lbl);
Bullets.Add(b);
}
}
public class Bullet
{
public Point Location { get; set; }
public Label BulletUI { get; set; }
public DateTime Created { get; set; }
public int Speed { get; set; }
public bool Destroy { get; private set; }
public Bullet()
{
Created = DateTime.Now;
}
public void Update()
{
Location = new Point(Location.X, Location.Y - Speed);
if (Location.Y <= 0 || (DateTime.Now - Created).TotalMilliseconds >= 5000)
{
Destroy = true;
return;
}
BulletUI.Invoke((MethodInvoker)delegate { BulletUI.Left = Location.X; BulletUI.Top = Location.Y; });
}
}
}