C# Backgroundworker quick overview
Posted by D#E on March 13, 2008
continuing from yesterday’s post in –HERE–
Today I tried out the backgroundworker component. It was actually a thread but being simplified and by using this component will make the code look neater. It also support the cancellation of thread. I used this backgroundworker as a process that will update the progress bar.
First thing you got to do is to drag the backgroundworker component on your windows application form.
to run the background worker use this code (for example inside button click)
backgroundWorker1.RunWorkerAsync();
and then you need to define what work it should do in DoWork function and as optional you could use the report progress too
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// write code here what do you want to do with the thread
//to report the progress use this
// backgroundWorker1.ReportProgress(10); // parameter is the percent completed
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
the nice thing is with ordinary thread, it won’t let you access some GUI handled interface. But by using the backgroundworker, you’re free to access GUI interface such as progressbar anytime you want. Pretty nice huh???? Think again.
if you read my previous post about delegate –HERE– you will notice that I used delegate to access the progressbar. And I tried to experiment it again here. by stripping the report progress and progress changed part and integrate some delegate in DoWork process, I got this result
| Method | Runtime |
| Using BackgroundWorker only | 46 seconds |
| Thread using delegate | 36 seconds |
| BackgroundWorker using delegate | 36 seconds |
| just a single main without progress bar | 10 seconds |
get the idea ? while backgroundworker could access all interface directly, it costs runtime performance. And for comparison, using no progress bar at all just cost 10 seconds on my program. They were all tested on same exact process. So THERE IS a trade off between good interface and performance cost. As a conclusion to this post, learning delegate won’t hurt if you’re planning to using thread.
Possibly related posts: (automatically generated)
This entry was posted on March 13, 2008 at 8:20 pm and is filed under IT Related. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
yonita said
backgroundworker ??
if we try to translate with divide it become three word ( back, ground, n worker ), new comer error. hehehhheheheh
D#E said
ni anak mo omong opo
Shakil Ahmad said
its a good article…
Guilherme said
Good Article…
Amit Hegde said
Hi,
Cool one…. Good observation and comparison… Thanks…. Keep up the good work….
Amit