C# tutorials
17. BackgroundWorker i

Note: While reading this page, bear in mind that I'm no computer expert and that the text below may be partly inaccurate. If you find errors or have proposals for improvements, please send me a message and help make this a better page for the benefit of future visitors. To the left, there are links to more C# tutorials.


With a BackgroundWorker, you can execute time-consuming operations, like complex computations or operations on very large files or very many files, in the background (meaning that you can move the mouse etc. while the BackgroundWorker is running).

To complete this tutorial, follow these instructions:

1. Open Visual C# 2010 Express.

2. Click on New Project in the File menu.

3. Choose Windows Forms Application if that option isn't already chosen, change the name if you like and click on OK.

4. Point at Toolbox in the left margin and click on the Auto Hide icon at the top of the window (to keep the window to stay open and easier to work with).

5. Drag a Button to Form 1.

6. Drag two Rich Textboxes to Form 1. Resize Form1 and the textboxes if you like.

7. Drag a BackgroundWorker to Form 1. It will appear at the bottom of the screen when you release the left mouse button.

8. Double-click on the button. The file Form1.cs will open with the caret ready to write code that will run when button 1 is clicked.

9. Write or paste this code where the caret is:

try
{
  startBgw();
}
catch (Exception excMsg)
{
  MessageBox.Show(excMsg.Message.ToString(), "Error");
}

10. Write or paste this code right above the line private void button1_Click(object sender, EventArgs e):

private void startBgw()
{
  if (richTextBox1.TextLength == 0)
  {
    MessageBox.Show("There's no text in richTextBox1.");
  }
  else
  {
    Class1 c1 = new Class1();
    c1.str = richTextBox1.Text;
    backgroundWorker1.RunWorkerAsync(c1);
  }
}

11. Right-click on backgroundWorker1 at the bottom of the Form1.cs[Design] tab and click on Properties.

12. Select WorkerReportsProgress in the properties pane and change the value to True.

13. Click on the Events flash at the top of the Properties pane.

14. Double-click on DoWork and write or paste this code where the caret is:

BackgroundWorker bgw = sender as BackgroundWorker;
Class1 c1 = e.Argument as Class1;
c1.ReplaceSpaces(bgw, e);

15. Return to the Form1.cs[Design] tab, double-click on ProgressChanged in the Properties pane and write or paste this code where the caret is:

Class1.progressReport pr = e.UserState as Class1.progressReport;
richTextBox2.Text = pr.message;

16. Return to the Form1.cs[Design] tab, double-click on RunWorkerCompleted in the Properties pane and write or paste this code where the caret is:

if (e.Error != null)
{
  MessageBox.Show(e.Error.Message);
}

17. Click on Add Class in the Project menu.

18. Choose Class if that option isn't already chosen, keep the name Class1.cs and click on Add.

19. Add this code right below using System.Windows.Forms;:

using System.ComponentModel;

20. Place the caret right after the first curly brace right below class Class1, press return and write or paste this code where the caret is:

public class progressReport
{
  public string message;
}

public string str;

public void ReplaceSpaces(BackgroundWorker worker, DoWorkEventArgs e)
{
  progressReport pr = new progressReport();
  if (str.Length > 1000000)
  {
    pr.message = "All spaces are being replaced.";
    worker.ReportProgress(0, pr);
  }
  string result = str.Replace(" ", "\n");
  pr.message = result;
  worker.ReportProgress(0, pr);
}

21. Press F5 to start debugging the program.

22. Click on the button. A message box with the text There's no text in richTextBox1. should appear.

23. Copy some text to richTextBox1 and click on the button. A text with all spaces replaced by linebreaks should appear in richTextBox2.

24. If you didn't do so in step 22, copy the text from a really large file (about 5 MB or more) to richTextBox1 and click on the button. The message All spaces are being replaced. should be shown in richTextBox2 for a few seconds before the text with all spaces replaced by linebreaks appears.

General comment

The comments below are notes I wrote while trying to figure out how a BackgroundWorker works rather than informed comments. In other words, expect at least some comments to be inaccurate or missing. I will try and improve the comments later.

Comment on the first code snippet

Line 3: Run the method startBgw (the code you copied right above the line private void button1_Click(object sender, EventArgs e)).

Comments on the second code snippet

This method does not run in the background.

Line 3-6: If richTextBox1 is empty, display a message.

Line 7-12: If richTextBox1 isn't empty, run line 9-11.

Line 9: Create a new instance of Class1.

Line 10: Get the text from richTextBox1 and connect the text to Class1 by adding c1. to the variable name str.

Line 11: Start the background operation and set what's run to c1 (Class1).

Comments on the third code snippet

This method runs in the background. This is where the actual work is done.

Line 1: Convert the object sender to a BackgroundWorker.

Line 2: Convert the object DoWorkEventArgs.Argument to Class1.

Line 3: Run the method ReplaceSpaces (in Class1.cs).

Comments on the fourth code snippet

This method does not run in the background.

Line 1: Convert the object ProgressChangedEventArgs.UserState to the class progressReport in the class Class1

Line 2: When the BackgroundWorker raises a ProgressChanged event, set the text in richTextBox2 to the string message.

Comment on the fifth code snippet

This method does not run in the background.

If something goes wrong during the background operation, display an error message.

Comment on the sixth code snippet

A BackgroundWorker needs the namespace System.ComponentModel to work.

Comment on the seventh code snippet

Line 1-4: Initialize the string message. It seems this string has to be put in a class, I'm not sure why.

Line 6: Initialize the string str, that is used in the method startBgw to get the text from richTextBox1.

Line 10: Create a new instance of the class progressReport.

Line 11-15: If the string str a.k.a. the text in richTextBox1 is longer than 1 million signs, tell the user what the BackgroundWorker is doing at the moment by displaying the message All spaces are being replaced. in richTextBox2. If you want to always display the message, remove the line if (str.Length > 1000000) and the two curly brackets ({ and }). However, if the text in richTextBox1 is shorter than, in the case of this program, about 1 million signs, the message All spaces are being replaced. is shown for such a short period of time that the user of the program won't be able to see the message, making it useless to show it.

Line 16: Replace every space in the string str with a linebreak and collect the result in the string result. This line is in principle a placeholder, that indicates where to put code you want the BackgroundWorker to run.

Line 17-18: Set the string message to the string result and display the string message in richTextBox2.


Would you like to comment on this page or some other page? Use the contact form. Write the title of the page you want to comment on and your comment in the field Message.