Threading in C#: Code Alert!

Okay, so you have a GUI, and you think you're sexy. Then you run some big task and cos you're not using threads your GUI is as useful as a pile of potatos at a cannibal convent. Unless I guess they had humans in cages and fed them potatos to fatten them up... anyway...

So you have say Form1 as ur form class, it helps to have your main method in there as well for shits and giggles, then when you clicky a button you can just do something like this:

MainClass main; /* The class that has the method we'll use */
Thread mainThread; /* The thread object itself */

/* Instantiate the object */
main = new MainClass(arg1, arg2, bla);

/* Instantiate the thread and define the method that will be used when the thread runs */
mainThread = new Thread(new ThreadStart(main.Go) );

/* Start the thread */
mainThread.Start();


And you're all like, "how terrible erogenous". If you want your method (Go) to have parameters, you have to do some delegating shit that I couldn't be bothered by. That's why all my arguments are parsed when I instantiate the mainclass. Also remember to slam using System.Threading; at the top.....

Then you're all like up in my grill saying "Hey Guy, I want to update some shitty form content up in here from my 2nd thread" so I'm like. K. When you instantiated the class object, parse though the form object you want to modify, set it as a global thing, then just have a method to change it:

private void ChangeStatus(){
if (labelstatus.InvokeRequired){
labelstatus.Invoke(new System.Windows.Forms.MethodInvoker(ChangeStatus));

}else{
labelstatus.Text = "Finished!";
}
}


If you don't do the invoking you get crazy errors like "Cross thread operation not valid: Go faceplant yourself"....

That's my c# tutorial for today. Apologises for the informal gangsta format.

0 comments:

General Ramblings and Observations by Tom of Earth: a cryptic emotionally-driven look into the life of times of the infamous sock wearer, gadget-whore, unintentional blasphemer, hypocrite, servant of Xenu, Pastafarian, absurdist and thantophobic...without me, its just aweso

Random Post!