Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use BackgroundWorker Control in C #

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to use the BackgroundWorker control in C#, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article on how to use the BackgroundWorker control in C#. Let's take a look.

In our program, there are often some time-consuming operations. In order to ensure the user experience and not cause the interface to be unresponsive, we generally use multithreading operations to allow time-consuming operations to be completed in the background. After completion, processing or prompts are given, while running, the progress bar on the interface will be refreshed from time to time, and if necessary, the background thread will be controlled to interrupt the current operation.

In. Net, a component BackgroundWorker is provided to solve this problem. The BackgroundWorker class allows operations to be run on separate dedicated threads. Time-consuming operations, such as downloads and database transactions, may cause the user interface (UI) to stop responding when running for a long time. If you need a responsive user interface and face long delays associated with such operations, you can easily use the BackgroundWorker class to solve the problem.

Program execution steps:

1. Call the RunWorkerAsync () method of BackgroundWorker. If the background operation requires a parameter, the parameter is given when the RunWorkerAsync () method is called. Inside the DoWork event handler, the parameter can be extracted from the DoWorkEventArgs.Argument attribute.

2. Execute the DoWork event, and the code that needs to be executed in the background is put into the DoWork event to be executed. When the RunWorkerAsync () method is called, BackgroundWorker starts performing background operations by triggering the DoWork event

Show the progress of the background operation:

In order to show the progress of the background operation, first make WorkerReportsProgress equal to true, and then call the ReportProgress () method of BackgroundWorker to pass the progress value of the completed operation. In addition, this method triggers the ProgressChanged event, in which the parameters passed by the main thread are received through an instance of ProgressChangedEventArgs.

Cancel the background operation:

In order for BackgroundWorker to cancel what is being done in the background, first set the value of the property WorkerSupportsCancellation to true. Then call the CancelAsync () method, which makes the property CancellationPending true, and using the CancellationPending property, you can determine whether to cancel the background asynchronous operation.

After the background operation is completed, feedback to the user:

When the background operation is completed, both completed and cancelled,RunWorkerCompleted () events will be triggered, and the completion result of the background operation can be fed back to the user by this method. The RunWorkerCompleted event handler is called after the DoWork event handler returns. Through it, we can do some operations after the operation, such as disabling the cancel button, exception handling, result display and so on. Note that if you want to get the e.Result, you need to set the e.Result property in the BGWorker_DoWork method. In addition, use the Cancelled property of the RunWorkerCompletedEventArgs instance to determine whether the Cancel operation terminates the background operation.

Return value from background operation

When the DoWork event is executed, the Result property of the DoWorkEventArgs instance returns the value to the user; in the RunWorkerCompleted event, the Result property of the RunWorkerCompletedEventArgs instance receives the value

Create an example of BackgroundWorkerDemo:

1. Create a new windows forms application, such as BackgroundWorkerDemo

two。 Drag a ProgressBar (progress bar) and a BackgroundWorker control onto the Form form, as shown in the figure:

Background code:

Using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Threading;namespace BackgroundWorkerDemo {public partial class FrmDemo: Form {/ / sets the path to generate temporary files static string strSaveDir = @ "F:\ training"; public FrmDemo () {InitializeComponent () / / display the execution progress of the background operation this.bgWork.WorkerReportsProgress = true; / / you can cancel the operation being performed in the background this.bgWork.WorkerSupportsCancellation = true } / start / private void btn_Start_Click (object sender, EventArgs e) {if (Directory.Exists (strSaveDir) = = false) {return;} btn_Start.Enabled = false Int count = Convert.ToInt32 (this.txt_File.Text.ToString (). Trim ()); / / set the progress bar this.proBar.Minimum = 0; this.proBar.Maximum = count; this.proBar.Value = this.proBar.Minimum / / start executing asynchronous threads, perform background operations, and pass parameters this.bgWork.RunWorkerAsync (count) to the background } / the task code to be processed by the background operation / private void bgWork_DoWork (object sender, DoWorkEventArgs e) {/ / get the value int fileCount= Convert.ToInt32 (e.Argument) of the parameter passed from the RunWorkerAsync () method Random rand = new Random (); byte [] buffer = new byte [2048]; for (int I = 0; I

< fileCount; i++) { try { string strFileName = Path.Combine(strSaveDir, i.ToString() + ".tmp"); using (var stream = File.Create(strFileName)) { int n = 0; int maxByte = 8 * 1024 * 1024; while (n < maxByte) { rand.NextBytes(buffer); stream.Write(buffer, 0, buffer.Length); n += buffer.Length; } } } catch (Exception ex) { continue; } finally { //报告进度 this.bgWork.ReportProgress(i + 1); Thread.Sleep(100); } //判断是否取消了后台操作 if (bgWork.CancellationPending) { e.Cancel = true; return; } //设置返回值 e.Result = 234; } } /// /// 更新前台界面进度条 /// /// /// private void bgWork_ProgressChanged(object sender, ProgressChangedEventArgs e) { //获取异步任务的进度百分百 int val = e.ProgressPercentage; this.label2.Text = string.Format("已经生成{0}个文件", val); //进度条显示当前进度 this.proBar.Value = val; } /// /// 后台操作完成,向前台反馈信息 /// /// /// private void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { btn_Start.Enabled = true; //用户取消操作(e.Cancelled==true,表示异步操作已被取消) if (e.Cancelled) { MessageBox.Show("用户取消后台操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("操作完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //接收返回值 int result = (int)e.Result; MessageBox.Show("返回值:" + result); } } /// /// 取消 /// /// /// private void btn_Cancle_Click(object sender, EventArgs e) { //调用CancelAsync(),取消挂起的后台操作 this.bgWork.CancelAsync(); } }} 运行界面: 操作完成界面: 接收返回值: 取消后台操作:

This is the end of the article on "how to use BackgroundWorker controls in C#". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use BackgroundWorker controls in C#". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report