I'm a beginner and doing some C# exercises. I found out about Forest Fire Model and tried to do this with WPF and for drawing, I'm using canvas by creating a rectangle for every pixel. The problem iam getting is that the Program freezes and canvas doesn't draw anything (with the while(true) loop). Also, I'm deleting all children after an iteration, still the program is collecting GBs of RAM.
Simplified Code for testing:
public partial class TestDrawing : Window
{
public TestDrawing()
{
InitializeComponent();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
DrawForestFire();
}
private void DrawForestFire()
{
Random rand = new Random();
while (true)
{
for (int y = 0; y < 100; y++)
{
for (int x = 0; x < 100; x++)
{
Rectangle rectangle = new Rectangle();
Color color = Color.FromRgb((byte)rand.Next(200),
(byte)rand.Next(200), (byte)rand.Next(200));
rectangle.Fill = new SolidColorBrush(color);
rectangle.Width = 4;
rectangle.Height = 4;
Canvas.SetTop(rectangle, y * 4);
Canvas.SetLeft(rectangle, x * 4);
canvas.Children.Add(rectangle);
}
}
canvas.Children.Clear();
}
}
}
I also tried to draw run the "DrawForestFire()" in a Thread, with the canvas Object in a "this.Dispatcher.Invoke(() => { ... });" but it didn't made any difference for me. What is going wrong?
And, is there something better than Canvas for this kind of operations?