BackgroundWorker Class Howto.
Well I wanted to go multithread in my .NET applications and my friend Joel gave me a mini class that could give anyone a head ache. What he taught me worked, and was the thing to do in the days of Visual Studio 2003, but I explored the new Background worker class, new to Visual Studio 2005.
You know how your application locks up when you run a long process? Threading lets sections of code run in the background, letting your application do other stuff. This mini howto shows a simple example of running some code in the background using the
BackgroundWorker Class for Visual Studio 2005.
The class lets you return an integer, and object. I use the integer as a switch in case I am monitoring different aspects of a process such as a progress bar, or status text. ( from the same background process )
First I initialize the worker in my class.
Then I set my event method in my class.
{
if (e.ProgressPercentage == 1)
{
this.txtStatus.Text = this.txtStatus.Text + e.UserState + “\r\n”;
}
if (e.ProgressPercentage == 2)
{
abProg prog;
prog = (abProg) e.UserState ;
progTb.Maximum = prog.max;
progTb.Minimum = prog.min;
progTb.Value = prog.val;
}
if (e.ProgressPercentage == 3)
{
abProg prog;
prog = (abProg)e.UserState;
progPage.Maximum = prog.max;
progPage.Minimum = prog.min;
progPage.Value = prog.val;
}
if (e.ProgressPercentage == 4)
{
this.lblSearchEngine.Text = (string) e.UserState;
}
if (e.ProgressPercentage == 5)
{
this.lblPage.Text = (string) e.UserState;
}
if (e.ProgressPercentage == 6)
{
this.txtTb.Text = this.txtTb.Text + e.UserState;
}
if (e.ProgressPercentage == 7)
{
this.lblLink.Text = (string)e.UserState;
}
}
Then inside a button click event or some other method I start the thread. RunGetTbs is the method local to my class that i am running.
worker.WorkerReportsProgress = true;
worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerAsync();
And here is the runGetTbs method. Notice I am sending something back to the worker object to report. You can send any object back, not just a string. Also notice that someMethod takes the worker object as a parameter. This is so you can report back on what is going. worker_ProgressChanged is called when you do a worker.ReportProgress.
{
worker.ReportProgress(1,”Trackback Finder Started…\r\n”);
object.someMethod(this.cdb,worker);
}
You’ll want to read more up on it for more options, but this is the basics. Good luck!
