Home | Applications | Documentation | Transport | Personal |

Documentation

Home | Cloud | C# | Database | DevOps | Revision | Web |

C# | API | Delegates | Dll | Garbage | Events | Interfaces | Lambdas | MVC | NoSql | Objects | Tasks | Worker |

C# Background Workers.

BackgroundWorkers

This page describes how Background Workers work. I will demonstrate how to use a worker in a windows form application.

Setup a new Form

This program is going to run a counter in the background and show a progress bar at the bottom of the form.
So. create a C# windows form with .Net Framework.
Add a button and call it btnStart with text = "&Start"
Add 3 text boxes, txtNumber, txtStart and txtEnd
Finally, add a progressBar to the bottom of the form.

Add the BackgroundWorker

First we need to go to the ToolBar and drag the BackgroundWorker on to the form. It will appear at the bottom of the page. Then select the component and change the WorkerReportsProgress to True.
Next we need to click on the Events button. Double click on the 3 events so that the solution will create methods. These are DoWork, ProgressChanged and RunWorkerCompleted. We now need to add code to these.
See the code below. It iterates from 1 to the number of seconds and keeps track of progress with the progress bar. It also records the end time.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i < Int32.Parse(txtNumber.Text); i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(0);
}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (progressBar1.Value != progressBar1.Maximum)
{
progressBar1.Value += 1;
}
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//MessageBox.Show("Done");
txtEnd.Text = DateTime.Now.ToLongTimeString();
}

Run the worker

We now need to run the background worker. Double click on the button. We will now setup the progress bar. Set the current value to 0 and the Maximum to the number in txtNumber. Set the current time in the txtStart text box and run the worker asynchonously using RunWorkerAsync().

Here is the code

private void btnStart_Click(object sender, EventArgs e)
{
progressBar1.Value = 1;
progressBar1.Maximum = Int32.Parse(txtNumber.Text);
txtStart.Text = DateTime.Now.ToLongTimeString();
backgroundWorker1.RunWorkerAsync();
}

Threads

As this worker is using threads, you will need the Thread class.
using System.Threading;
The worker can use the components on the form, but if you try to change any component that is being used by the worker, you may get an error saying that you can't use this as it is being used by another thread.

Adding to event handlers

This is being worked on and will be updated soon.....