C#. Control (component) BackgroundWorker




Control (component) BackgroundWorker. Working with threads (background operations). Overview of methods, properties, events


Contents


Search other websites:

1. BackgroundWorker control. The purpose

The BackgroundWorker control (component, class) implements the execution of a separate thread in Windows Forms applications. To use the capabilities of the BackgroundWorker, you need to place it on the form (Figure 1).

C#. Windows Forms. The BackgroundWorker control

Figure 1. Placing the BackgroundWorker component to the ToolBox panel that on the form

After placement, the system will create an appropriate instance of the BackgroundWorker type and give it a default name. Figure 1 creates an instance (object) named backgroundWorker1. For the created instance, the system offers a number of properties and events, which are described below.

 

2. Properties of BackgroundWorker control

When an instance of the BackgroundWorker type is activated, a list of properties of this control is displayed (Figure 2).

C#. Windows Forms. List of properties of the BackgroundWorker control

Figure 2. List of properties of the BackgroundWorker control

 

2.1. Property Name. Set the name of the class instance

The Name property specifies the name of the instance of the BackgroundWorker class. The system automatically generates default names. The first instance in the program is named backgroundWorker1, the second instance is backgroundWorker2, and so on. You can optionally change the name of the BackgroundWorker instance.

C#. Windows Forms. The BackgroundWorker control. Property Name

Figure 3. The BackgroundWorker control. Property Name = backgroundWorker1

 

2.2. Property GenerateMember. The presence/absence of an instance of a class

The GenerateMember property specifies the presence/absence of an instance of the BackgroundWorker class. If GenerateMember = true (default), then the system will generate an instance with the name specified in the Name field (backgroundWorker1 by default) in the Form1.Designer.cs file

partial class Form1
{

  ...

  private System.ComponentModel.BackgroundWorker backgroundWorker1;
}

here

  • Form1 – the name of the instance of the main form of the program;
  • backgroundWorker1 – the name of the thread instance.

If GenerateMember = false, then no instance is created. If during the program operation it is necessary to refer to an instance of the BackgroundWorker class, then it is imperative to set this property to true.

C#. Windows Form. BackgroundWorker control. GenerateMember property

Figure 4. Generating an instance if GenerateMember = true

 

2.3. Property Modifiers. Visibility from other forms or classes

The Modifiers property is intended to set the visibility of an instance of the BackgroundWorker type (Figure 5). The property can take one of the following values:

  • private;
  • protected;
  • public;
  • internal;
  • protected internal.

You can read more about using class member access modifiers here.

C#. Windows Forms. BackgroundWorker control. Property Modifiers

Figure 5. Property Modifiers

If for an instance of the BackgroundWorker type in the properties window you set, for example, the value

Modifiers = public

then the part of the Form1 class, which is located in the Form1.Designer.cs file, will contain a public declaration of the instance of the BackgroundWorker type

...

partial class Form1
{

  ...

  public System.ComponentModel.BackgroundWorker backgroundWorker1;
}

...

This means that the backgroundWorker1 instance will be visible from other modules, namespaces, classes, etc.

 

2.4. Property WorkerReportsProgress. Set the possibility of adjusting the execution process

The WorkerReportsProgress property determines whether the program should display the progress of the thread (progress). Figure 5 shows the configuration properties to False.

C#. Windows Forms. BackgroundWorker control. Property WorkerReportsProgress

Figure 6. Property WorkerReportsProgress

The program code for declaring a property in the BackgroundWorker class looks like

public bool WorkerReportsProgress { get; set; }

If WorkerReportsProgress = true, then you can display a progress report (progress) by calling the ProgressChanged() method. Otherwise, displaying the progress of the thread will fail and calling the ProgressChanged() method will result in an error.

More details on how to implement thread progress can be viewed here.

 

2.5. Property WorkerSupportsCancellation. Set the ability to cancel the execution of a thread

The WorkerSupportsCancellation property allows you to specify whether a thread can be canceled. Figure 7 shows how a property is set in design mode.

C#. Windows Forms. BackgroundWorker control. Property WorkerSupportsCancellation

Figure 7. Property WorkerSupportsCancellation

According to the documentation, the property declaration looks like:

public bool WorkerSupportsCancellation { get; set; }

If the property is true, then the thread supports asynchronous cancellation. For a thread instance backgroundWorker1 in the program, this property can be changed as follows

...

// Setting property programmatically
backgroundWorker1.WorkerSupportsCancellation = true;

...

 

2.6. Property CancellationPending. Determining whether a thread has been canceled

The CancellationPending property is used to determine whether a background operation (thread) has been canceled. The property declaration is as follows:

public bool CancellationPending { get; }

By default, the property is set to false. Checking the value of the CancellationPending property needs to be written into the DoWork event handler.

Example.

// Thread execution, DoWork event handler
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

  ...

  // Thread execution loop
  for (int i=0; i<1000; i++)
  {
    ...

    // Checking if the command to cancel execution of the thread has been executed
    if (backgroundWorker1.CancellationPending)
      break;
  }
}

 

2.7. Property isBusy. Checking if a thread is currently running

The isBusy property returns a value that determines whether the BackgroundWorker instance performs an asynchronous operation. In other words, isBusy determines whether the thread associated with the BackgroundWorker instance is currently executing. The property declaration is as follows

public bool IsBusy { get; }

The isBusy property does not appear in the Properties window. This property is used directly in the program.

If the thread corresponding to the backgroundWorker1 instance is running, it means that the following method was called

backgroundWorker1.RunWorkerAsync();

If you try to call this method again on this instance, an exception will be thrown. This is because the backgroundWorker1 thread is still running and busy. That is why the isBusy property is used to check if a thread is busy.

In view of the above, the event handler for starting a thread for execution should look like this

// Run the thread
private void button1_Click(object sender, EventArgs e)
{
  // Start a thread checking if it is busy
  if (!backgroundWorker1.IsBusy)
    backgroundWorker1.RunWorkerAsync();
}

 

3. The methods of BackgroundWorker class
3.1. Method ReportProgress(). Show progress of thread execution

The ReportProgress() method raises the ProgressChanged event, in which you can set the visualization of the progress of the task. According to the documentation, the method has two overloaded implementations. The most used of them is the following

public void ReportProgress(int percentProgress);

here

  • percentProgress – an integer value between 0 and 100 indicating the percentage of work completed.

This method can be called only if the WorkerReportsProgress property is set to true (see section 3.4). If WorkerReportsProgress is set to false, then calling the method will throw a System.InvalidOperationException.

Example. To display a value equivalent to 55 percent, you need to write the following code

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  ...

  try
  {
    // indicate 55 percent of completed work in the thread
    backgroundWorker1.ReportProgress(55);
  }
  catch (InvalidOperationException exception)
  {
    // Display error message
    MessageBox.Show(exception.Message);
  }

  ...
}

 

3.2. Method RunWorkerAsync(). Starting a background operation (thread)

The RunWorkerAsync() method is designed to start a thread for execution. The method declaration is as follows

public void RunWorkerAsync();

For example, for an instance named backgroundWorker1, the background operation (thread) will start as follows

// Start the thread
if (!backgroundWorker1.IsBusy)
  backgroundWorker1.RunWorkerAsync();

 

3.3. Method CancelAsync(). Cancel background operation

The CancelAsync() method requests the cancellation of the background operation (thread). The method declaration is as follows

public void CancelAsync();

To use the CancelAsync() method, the WorkerSupportsCancellation property must be true. Otherwise, an InvalidOperationException exception will be thrown.

Example.

...

// Cancel thread execution
try
{
  backgroundWorker1.CancelAsync();
}
catch(InvalidOperationException exception)
{
  // Display the error message
  MessageBox.Show(exception.Message);
}

...

 

4. Events

The BackgroundWorker class contains the following basic events:

  • DoWork – occurs after the thread is started by the RunAsync() method. The thread execution code is written into the handler for this event. Such code can be, for example, a loop for sorting an array, searching for data in an array, etc.;
  • ProgressChanged – occurs when a workflow indicates that some progress has been made. To trigger the ProgressChanged event, the DoWork event handler is indicated when the progress has been changed (reached) using the ReportProgress() method. In turn, raising the ProgressChanged event will trigger the event’s handler. The ProgressChanged event handler specifies the code for rendering progress using well-known components such as ProgressBar, Label, etc.;
  • RunWorkerCompleted – raised when a thread of execution completes. The termination of a thread can be due to work completed, an error occurred, or the execution of the thread was canceled. It is advisable to write the code of the final operations, output the corresponding messages, etc. into the handler of this event.

The event list box for the BackgroundWorker control is shown in Figure 8.

C#. Windows Forms. The events of BackgroundWorker control

Figure 8. The events of BackgroundWorker control

You can read more about the interaction between the event handlers DoWork, ProgressChanged, RunWorkerCompleted in the next topic.

 


Related topics