Hi all,
I am currently working on a "game of life" program. Which basically updates a grid and forms interesting patterns.
Now part of the program means it has to have a "start" and "stop" button. The idea being that the user can click one button to start the game of life animating, and the next button to stop the animation.
Now obviously to allow the user to have control over the GUI elements, I have incorporated a background thread to allow this. However I have problems when I run the program :(
Some background:
The "grid" is basically a stretched bitmap with the pixels acting as cells. The game of life checks how many pixels around it are occupied, and then works out if the cell should be "Alive" or "Dead" in the next iteration.
i.e. if pixel if populated and has 3 neighbors it lives. Draw it on the next bitmap. Swap the old bitmap with the new one and Refresh to show the next iteration.
Now this works fine when I don't use a background thread, and just go through the iterations step-by-step.
The problem is now that I have used this background thread, and click start, the animation works fine. Up until I move my mouse of off the button. When I move my mouse from the button it throws "InvalidOperationException was unhandled by user code - Object is currently in use elsewhere" I'm pretty sure this is because my mouse is moving and causing the form to animate in some way.
Does anyone have any ideas/suggestions on how to fix this? I've spent a few days and think I've hit a brick wall with this. Code beneath.
//Throws the error on one of the lines testing the neighboring cell. Like this one:
testn = CurrentBitmap.GetPixel(x - 1, y);
//incorporation of background worker
if (loopbreak == null)
{
start = true;
loopbreak = new BackgroundWorker();
loopbreak.DoWork += new DoWorkEventHandler(loopbreak_commence);
loopbreak.RunWorkerAsync();
}
//Apply the rules on click
private void loopbreak_commence(object sender, DoWorkEventArgs e)
{
while (start == true)
{
if (!start)
{
start = false;
break;
}
applyrules();
SwapImages();
//invoke the refresh
Invoke(new MyDelegate(refr), true);
}
}
//invoke refresh - This isn't the problem. Error still occurs when this is commented out
delegate void MyDelegate(bool refr);
public void refr(bool refr)
{
Refresh();
}