C# Using BackgroundWorker – Programming, Pseudocode Example, C# Programming Example
Windows Form WPF Form

C# Using BackgroundWorker

BackgroundWorker In C#

In the case of time-consuming tasks (eg reading a very large text file), it can happen that the form freezes, so to speak. This happens because everything runs in one thread and so the form has no chance to respond to user input or to redraw. The easiest way to simulate such a behavior is to install a Thread.Sleep (10000) (previously using System.Threading). This will freeze the mold for 10 seconds.

To prevent this freezing, there is the threading namespace. There are tons of ways to create more threads (multithreading). To simplify this complicated topic of threading, .NET introduced the BackgroundWorker. I would like to show you this with an example.

Create a Windows Forms project and add a Button (btnStartEnd) and a Progressbar (progressBar1) to it and switch to the Code view.

Here we first add the Using.

We create the mentioned background worker globally in the class Form1


Global BackgroundWorker variable


Form Load Event


In the Form Load event, we first create a new instance of the background worker and set the WorkerReportsProgress and WorkerSupportsCancellation properties to true.
WorkerReportsProgress: Needed while the BackgroundWorker is busy, passing statuses to the form to indicate the progress.
WorkerSupportsCancellation: So that we can cancel the processing in the BackgroundWorker at any time.

Then we register the required events of the background worker to respond to each incident.

DoWork Event of the BackgroundWorker

In the DoWork – Event now comes the time-consuming code part in which the form would freeze in the normal case.
It should be noted that in this event NOT UserControls may be accessed, since we are not allowed to pass over cross-thread values ​​(unless we use Invoke).
In the event, we first assign a percentage value if the worker has been stopped and the task is now to be continued.
Then we create a while loop that runs until 100% has been reached or the thread has been stopped with CancelAsynch (). In the while loop, we increment the% status and tell the background worker that something has changed by calling the ReportProgress method. So that the thread is not finished too fast and for a better view, I have a Thread.Sleep of 50 milliseconds installed. At the end of the DoWork event we give the current percentage as Result.

ProgressChanged event of the backgroundworker

The ProgressChanged event is called whenever the ReportProgress() method of the BackgroundWorker is called (used at the top of the DoWork event).
All we do here is to update the value of ProgressBar. We get the current percentage from the ProgressChangedEventArgs.

RunWorkerCompleted Event of the BackgroundWorker

As the EventName suggests, the RunWorkerCompleted event is called as soon as the backgroundworker finishes his task. He makes no distinction whether the processing has now run to the end or the code was aborted by setting the CancelAsync ().
In a MessageBox we now show up to how many% of the BackgroundWorker has arrived and give the button the text “Start” again to let the Backgroundworker either restart or continue running.

Now only the handling of the button is missing.

Click event of the button



If BackgroundWorker is busy, it should be stopped using CancelAsync (). This internally sets the CancellationPending flag to true. In addition, we put the ButtonText back on startup if we want to keep the BackgroundWorker running.
If the BackgroundWorker is not busy, check if the Progressbar already has the maximum value at the time. If this applies, we set it back to the minimum value.
Regardless, the BackgroundWorker is started by using RundWorkerAsync (). As parameter we pass the current ProgressBar value. The button Text we still set to Stop, if the user wants to cancel the BackgroundWorker.

That’s it. Here’s a screenshot of what it might look like:

All Code:



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.