Wednesday, March 09, 2005

Once again, last night I did nothing! Well actually I surprisingly went to International Laddies Day but that's an aside.

So today I once again have some free time so I added a little more to the world generator - namely I made it a Threaded Application. In C# this is painfully simple. The last time I did threads was in C on Linux and I remember it being unpleasent.

This was a snap and it's safe too. It's impossible to have threads accessing any resources at the same time. So now you press the "Grow" button and it grows in real time!

(I also noted a small bug where I was allowing coordinates to equal 100! Oops should be 99, should really be bitmap.length-1 but what are you going to do.)

So that's something that's keeping me occupied today. Really the method of generation needs changing too.

Extremely Quick Guide to how I added Threading

First you need the resources:

using System.Threading;


Then I wanted to have a thread object in my class. I wasn't very original in it's naming.


Thread thread;


Then everytime I press "Grow" I need to make a new thread and start it. I also need to turn off the input buttons to prevent any resouce conflicts. (Probably anyway :D I mean some how the bitmap is being published to the screen every cycle and yet also updated by the thread - I assume this is automagically taken care of by C# some how :D)


private void button1_Click(object sender, System.EventArgs e)
{
//Grow the map
thread = new Thread(new ThreadStart(this.GrowMap));
thread.Name = "Map Growing Thread";
thread.Start();
}


This say's when you press the Grow button then start the thread up.


private void GrowMap()
{
DisableControls();
int growthAmount = (int)numericUpDown2.Value;
listBox1.Items.Add("Growing for "
+ growthAmount + " iterations.");

for(int i = 0; i < growthAmount; i++)
{

Grow(bitmap);
pictureBox1.Refresh();
Thread.Sleep(1);
}

pictureBox1.Refresh();
EnableControls();
}


Disable the controls merely set the Enabled bools to button1 and button2 to false. Enable controls set's them back to true. I don't want to be messy with the same resources my therad is messing with.

I tell the picture box to update. After I've finished a round of growing it. Then I pass control back to the form. Then the form grabs publishes the new results to the screen. Therefore there's no conflict of interest between the thread and the main loop - yay!

So anyway no you press Grow and it looks like a living organism it's cool.



I also changed the background colour to a less eye arresting blue.
Post a Comment