Microsoft has provided BackgroundWorker class which make it really easy to create background threads easily. Sometimes we need to implement so functionalities in background threads so that UI will not freeze, that is when this class comes handy. Obviously we can create our own threads and manage there lifecycle ourselves but not everyone is efficient with threads and also sometimes the complexity hits back by consuming lot of time which we really do not have in case of rapid application development.
When to use:
Downloading a large file and showing progress bar.
Uploading some information in background but letting the user to work.
Creating a polling application etc.
Usage:
BackgroundWorker is also present in the toolbox and you can drag it from there or like any other control you can create an object at runtime and use it on the fly.
It comes with various events and properties, few of them which are really important are:
DoWorkEventHandler (event)
This event binds the method (worker method) where you will your process intensive work (which you want to execute in background)
Worker method’s signature
void method_name (object sender, DoWorkEventArgs e)
DoWorkEventArgs e
Contains e.Argument and e.Result, so it is used to access those properties.
e.Argument
Used to get the parameter reference received by RunWorkerAsync.
e.Result
Check to see what the BackgroundWorker processing did.
|
RunWorkerCompletedEventHandler (event)
This event is fired once the background process has completed.
Completed method’s signature
void method_name(object sender, RunWorkerCompletedEventArgs e)
|
RunWorkerAsync (method)
This method is the staring point for background process. It takes an object as its argument and thus you can very well pass object of any type to it.
|
Here is a simple program which starts a background thread, sleeps for some time in worker method and then displays the message on completion of background process.
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private BackgroundWorker worker;
private void button1_Click(object sender, EventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
}
void worker_DoWork(object sender,DoWorkEventArgs e)
{
Work();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("slept enough");
}
private void Work()
{
for (int i = 0; i < 1; i++)
{
System.Threading.Thread.Sleep(1000);
MessageBox.Show("sleeping : " + i);
}
}
}
Comments
Post a Comment