Background worker in .NET

Tram Ho

Hi guys, wish everyone a productive and energetic day. Today I will introduce about background workers in .NET.

Don’t let you wait long, let’s start with the article. In this article, I will talk about the definition, properties, methods, events and how to use background workers in .NET.

1. What is a background worker?

  • BackgroundWorker is a class provided by the .NET Framework to perform long-running tasks or synchronous work on an independent thread, helping to avoid application block when performing tasks. heavy duty.
  • BackgroundWorker is commonly used in Windows Forms or WPF applications to perform time-consuming tasks and update the UI continuously.
  • Background workers are not available with .NET core. But .NET framework, .NET 5 and .NET 6 (long-term support) have support.

Note: but one note is that with .NET 5 and .NET 6, it is not recommended to use Background workers. It is recommended to use Task-based Asynchronous Programming (TAP) like tasks, async, await.. to perform long-running tasks.

2. Benefits of using background workers

  • Avoid blocking UI: If you do heavy work in the main program (UI thread), it can block the application, making it impossible for users to interact with the application while these jobs are being done. BackgroundWorker helps to perform these jobs on an independent thread, avoiding application block and allowing users to continue interacting with the application.
  • Update job progress: BackgroundWorker provides the ProgressChanged event, which allows you to update the progress of work on the UI continuously. This helps the user to know the status of the work and increases the user experience.
  • Easy task management: BackgroundWorker provides methods for task management, allowing you to start or cancel tasks easily.
  • Easy integration into Windows Forms or WPF applications: BackgroundWorker is designed for easy and flexible integration into Windows Forms or WPF applications.

3. Properties in the background worker

Here are some commonly used attributes and examples:

  • WorkerReportsProgress: Get or Set the value that allows BackgroundWorker to support progress reporting. Progress reported events in BackgroundWorker are used to notify the progress of a background job to the UI thread. When the WorkerReportsProgress property is set to true, you can use the ReportProgress method to report the progress of background work.

  • WorkerSupportsCancellation: The WorkerSupportsCancellation property in the BackgroundWorker is used to allow the user to cancel a running background job. When this property is set to true, you can use the CancelAsync method to cancel a background job.

  • CancellationPending: Gets the value to check if the user has requested to cancel the execution of a background job. Returns boolean.

  • IsBusy: Gets the value indicating whether the BackgroundWorker is running a background activity.

  • DoWorkEventArgs: Gets the argument passed to the DoWork event handler.

  • Error: Get error if any error occurs during execution of background activity.

  • Result: Get the result of the background activity.

4. Methods in the background worker

  • CancelAsync() : Request to cancel the job in progress by setting the CancellationPending value to true.
  • ReportProgress(int percentProgress, object userState) : Report the progress of the work in progress and pass additional data (if any) via the userState argument.
  • RunWorkerAsync(object argument) : Send request to start background job execution and pass parameters (if any).
  • Dispose() : Releases resources used by BackgroundWorker.

In addition, BackgroundWorker also provides events to allow the application to respond when a job is running:

  • DoWork : The event that occurs when the job starts executing.
  • ProgressChanged : Event occurs when the progress of the job is reported.
  • RunWorkerCompleted : Event occurs when the job is completed or cancelled.

5. Some use cases use background workers

  • Downloading large data from the Internet: When the application needs to download large data from the internet, doing it in the UI thread itself will make the application freeze and become unresponsive. In this case, the Background Worker can be used to load the data in the background, and update the progress of the data loading via the ProgressChanged event.
  • Handling Big Data: When the application needs to process big data, for example image format conversion, doing it in the UI thread itself will cause the application to freeze and become unresponsive. In this case, the Background Worker can be used to process the data in the background, and update the progress of the processing via the ProgressChanged event.
  • Sending Emails: When the app needs to send emails, doing so in the UI thread itself causes the app to freeze and become unresponsive. In this case, it is possible to use the Background Worker to send emails in the background, and update the email delivery progress via the ProgressChanged event.
  • Read data from file: When the application needs to read data from a large file, doing so in the UI thread itself will cause the application to freeze and become unresponsive. In this case, the Background Worker can be used to read the data in the background, and update the progress of the reading via the ProgressChanged event.
  • Complex computations: When the application needs to perform complex calculations, such as calculating curves in graphics, doing so in the UI thread itself will make the application freeze and unresponsive. In this case, it is possible to use the Background Worker to calculate in the background, and update the progress of the calculation via the ProgressChanged event.

Example of using background workers when downloading data from the internet:

Share the news now

Source : Viblo