


This article mainly introduces the detailed explanation of the use of C# BackgroundWorker. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
In C# programs, there are often some CPU-intensive operations that take a long time. If such operations are performed directly on the UI thread, the problem of UI unresponsiveness will occur. . The main way to solve this kind of problem is to use multi-threading, start a background thread, and complete the computing operations in this background thread. However, the thread operation of the native interface is somewhat difficult. If you want to further complete the communication between threads, it will be even more difficult.
Fortunately, .NET Class Library provides a class called BackgroundWorker that can solve this type of problem more elegantly. Although the BackgroundWorker class is relatively simple to use, there are still some details that need to be paid attention to. Below we will introduce its main usage through the demo program. We calculate the cumulative sum from 1 to 100 in the demo. For demonstration, each calculation sleeps for 600 milliseconds. The UI of the demo is:
Usage Overview
Build a BackgroundWorker instance on the form, add time-consuming operations to its DoWorkevent handlingfunction, and then call its RunWorkerAsync method. .
private BackgroundWorker _demoBGWorker = new BackgroundWorker(); _demoBGWorker.DoWork += BGWorker_DoWork; _demoBGWorker.RunWorkerAsync(); private void BGWorker_DoWork(object sender, DoWorkEventArgs e) { //在这里执行耗时的运算。 int sum = 0; for (int i = 0; i <= 100; i++) { sum += i; } }
Is it a bit too simple? So let's consider the following question:
What if we want to pass parameters to the operation process?
What should we do if we want to display real-time information on the UI during the calculation process?
What if we want to cancel the ongoing operation?
What should we do if an exception occurs during the operation?
Next we will deal with these problems one by one.
Pass parameters to the calculation process
It is not good to directly write 100 into the calculation process. We also plan to allow users to specify the range of the sum! So you need to pass 100 as a parameter to the calculation process. In the overview, we start the calculation process by calling the RunWorkerAsync method. In fact, this method can accept an object type parameter. Through it, we can pass any data to the calculation process:
//别忘了设置滚动条。 this.progressBarSum.Maximum = 100; _demoBGWorker.RunWorkerAsync(100); //下面是更新后的 BGWorker_DoWork 方法: private void BGWorker_DoWork(object sender, DoWorkEventArgs e) { //在这里执行耗时的运算。 int endNumber = 0; if(e.Argument != null) { endNumber = (int)e.Argument; } int sum = 0; for (int i = 0; i <= endNumber; i++) { sum += i; } }
BGWorker_DoWork event processing function passes the calculation information we expect through the Argument attribute of parameter e.
Transfer the message to the UI
Since the calculation process is relatively long, while we display the current progress through the progress bar, we also hope to Display the intermediate results of the calculation on the UI in real time. Of course, BackgroundWorker also provides great support for this use case. It allows us to send messages to the UI thread during the calculation process. Let's take a look at the specific method:
_demoBGWorker.WorkerReportsProgress = true; _demoBGWorker.ProgressChanged += BGWorker_ProgressChanged;First, set the WorkerReportsProgress property to true, and then add processing for the ProgressChanged event. Method:
private void BGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { //修改进度条的显示。 this.progressBarSum.Value = e.ProgressPercentage; //如果有更多的信息需要传递,可以使用 e.UserState 传递一个自定义的类型。 //这是一个 object 类型的对象,您可以通过它传递任何类型。 //我们仅把当前 sum 的值通过 e.UserState 传回,并通过显示在窗口上。 string message = e.UserState.ToString(); this.labelSum.Text = message; }Continue to update BGWorker_DoWork method:
private void BGWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bgWorker = sender as BackgroundWorker; int endNumber = 0; if(e.Argument != null) { endNumber = (int)e.Argument; } int sum = 0; for (int i = 0; i <= endNumber; i++) { sum += i; string message = "Current sum is: " + sum.ToString(); //ReportProgress 方法把信息传递给 ProcessChanged 事件处理函数。 //第一个参数类型为 int,表示执行进度。 //如果有更多的信息需要传递,可以使用 ReportProgress 的第二个参数。 //这里我们给第二个参数传进去一条消息。 bgWorker.ReportProgress(i, message); Thread.Sleep(600); } }OK, now you can see the update of the progress bar and execution information.
Cancel operation
Allowing users to cancel the current operation during execution is a basic design, and BackgroundWorker naturally has good support:_demoBGWorker.WorkerSupportsCancellation = true;Same as the WorkerReportsProgress attribute, if we want to support cancellation operations we need to set the WorkerSupportsCancellation attribute to true. And we need to support it in the BGWorker_DoWork method. Add code after Thread.Sleep(600) in the for
loop:
bgWorker.ReportProgress(i, message); Thread.Sleep(600); //在操作的过程中需要检查用户是否取消了当前的操作。 if (bgWorker.CancellationPending == true) { e.Cancel = true; break; }If the cancel
button clicked by the user is detected , just exit the current calculation process. The following is the code to be called when clicking the cancel button:
_demoBGWorker.CancelAsync();Cancel operation is now supported, try it now! What to do if an exception occurs during calculation? Is there a way to know that the calculation process has ended? Of course there is, even if it ends normally, we still need to get the calculated results.
_demoBGWorker.RunWorkerCompleted += BGWorker_RunWorkerCompleted; private void BGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //如果用户取消了当前操作就关闭窗口。 if (e.Cancelled) { this.Close(); } //计算已经结束,需要禁用取消按钮。 this.btnCancel.Enabled = false; //计算过程中的异常会被抓住,在这里可以进行处理。 if (e.Error != null) { Type errorType = e.Error.GetType(); switch (errorType.Name) { case "ArgumentNullException": case "MyException": //do something. break; default: //do something. break; } } //计算结果信息:e.Result //use it do something. }RunWorkerCompleted event handler function will be called after the DoWork event handler function returns. Through it, we can perform some operations after the operation, such as disabling the cancel button, exception handling, result display, etc.
e.Result = sum;Summary, the BackgroundWorker class is fully functional and easy to use , it is really a powerful tool for handling asynchronous time-consuming operations!
The above is the detailed content of Detailed explanation of the usage of BackgroundWorker in C# (picture). For more information, please follow other related articles on the PHP Chinese website!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
