Use of the BackgroundWork class

Source: Internet
Author: User

Recently, I wrote a small game and wanted to use kinect to implement somatosensory control. Therefore, the data processing for the kinect should be placed in the background thread. This can be achieved through multithreading or parallel processing, however, the BackgroundWork class can get twice the result with half the effort. The following describes the knowledge about this class:

The BackgroundWork component is mainly used to implement multi-threaded programming. It places complex operations in the program in the background thread and interacts with the foreground in real time to achieve a quick system interaction experience.

The main attribute and method of BackgroundWork. The event is as follows:

Important attributes:

1. CancellationPending gets a value indicating whether the application has requested to cancel background operations. By judging the CancellationPending attribute in the DoWork event, you can determine whether the background operation needs to be canceled (that is, the end thread );

2. IsBusy gets a value indicating whether the BackgroundWorker is running an asynchronous operation. The IsBusy attribute is used in the program to determine whether background operations are in use;

3. WorkerReportsProgress gets or sets a value that indicates whether the BackgroundWorker can report progress updates.

4. workersuppscanscancellation gets or sets a value that indicates whether BackgroundWorker supports asynchronous cancellation. Set workersuppscanscancellation to true so that the program can call the CancelAsync method to submit a request to terminate the suspended background operation;

Important methods:

1. CancelAsync requests to cancel pending background operations

2. RunWorkerAsync starts to perform background operations.

3. ReportProgress raises the ProgressChanged event.

Important events:

1. occurs when DoWork calls RunWorkerAsync.

2. ProgressChanged when ReportProgress is called

3. RunWorkerCompleted occurs when the background operation is completed, canceled, or exception is thrown.

There are also three important parameters: RunWorkerCompletedEventArgs, DoWorkEventArgs, and ProgressChangedEventArgs.

The Calling mechanism and sequence of attributes, methods, and events of BackgroundWorker:

It can be seen that three important parameter transfer processes occurred throughout the life cycle:

Parameter Pass 1: This Parameter Pass is to pass the Object in RunWorkerAsync (Object) to the DoWorkEventArgs of the DoWork event. argument, because only one parameter can be passed here, in actual application, encapsulate a class, and pass the entire instantiated class as the Object of RunWorkerAsync to DoWorkEventArgs. argument;

Parameter transfer 2: This is to pass the program running progress to the ProgressChanged event. In actual use, it is often used to update the progress bar or log information for methods and events;

Parameter transfer 3: Before the DoWork event ends, the Result data generated by the background thread is assigned to DoWorkEventArgs. Result, while calling the RunWorkerCompleted event RunWorkerCompletedEventArgs. Result attribute in the RunWorkerCompleted event to obtain the Result generated by the background thread.

In addition, we can see that the DoWork event is run in the background thread, so the user interface content cannot be operated in this event. If you need to update the user interface, you can use the ProgressChanged event and RunWorkCompleted event.

After understanding the event calling sequence and parameter passing mechanism of BagkgroundWorker, it is much easier to use this component for multithreaded programming. The following is a small example of BackgroundWork multithreading.

Refresh the progress bar in the form. The following is

Drag the backgroundWorker component into the interface and respond to the three events. C # The Code is as follows:

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; namespace multithreading small example {public partial class Form1: Form {public Form1 () {InitializeComponent () ;}// response message is used here, private void backgroundworkerprogress progresschanged (object sender, ProgressChangedEventArgs e) {this. progressB Ar1.Value = e. progressPercentage; this. label1.Text = e. userState. toString (); this. label1.Update () ;}// message processing after the background work is completed. You can perform subsequent processing here. Private void backgroundworkerappsrunworkercompleted (object sender, RunWorkerCompletedEventArgs e) {MessageBox. show ("Operation completed");} // here, the place where the work function is called when the background process starts to work. You can write your existing processing functions here. Private void backgroundworker=dowork (object sender, DoWorkEventArgs e) {work (this. backgroundWorker1);} // real processing work private bool work (BackgroundWorker bk) {int tatle = 10000; for (int I = 0; I <tatle; I ++) {if (bk. cancellationPending) // determine whether the user needs to cancel the background and exit as soon as possible. {Bk. reportProgress (I, String. format ("the current value is {0}, the operation is interrupted by user application", I); return false;} // in the Process of processing, through this function, report the processing progress to the main thread. It is best to convert it into a percentage, which must correspond to the maximum value of the external progress bar. Here, I did not translate, but adjusted the maximum progress bar value of the interface thread to be consistent with the total number here. Bk. reportProgress (I, String. format ("the current value is {0}", I);} return true;} private void button2_Click (object sender, EventArgs e) {// when the user requests cancellation, let's take a look. Sometimes it's not so clever. This. backgroundWorker1.CancelAsync ();} private void button#click (object sender, EventArgs e) {// this sentence is used to start background work. This. backgroundWorker1.RunWorkerAsync ();} private void button3_Click (object sender, EventArgs e) {this. Close ();}}}

Through the introduction of BackgroundWork, we can know its advantages in implementing multi-threaded programming. The code is concise and easy to control. In addition to this class, we usually use the following methods:

1. the delegated asynchronous call uses a specific time-consuming operation as a delegate and uses BeginInvoke to asynchronously execute this delegate (Invoke is a synchronous call ), you can also input parameters for this operation and obtain the returned value through the EndInvoke method.

2. Use ThreadPool to create a self-contained WaitCallback delegate in. net FrameWork, and then place it in the thread pool to run ThreadPool. QueueUserWorkItem (callback). According to the definition of the WaitCallback delegate, You can input an object-type parameter. However, you cannot precisely control the threads in the thread pool.

3. Compared with ThreadPool, Thread overhead is relatively large. However, it has its advantages. The Thread class can be used to explicitly manage threads. Use the ThreadPool class to create a thread whenever possible. However, in some cases, you still need to create and manage your own threads, rather than using the ThreadPool class. In. net 2.0, a new delegate ParameterizedThreadStart is provided to support starting a thread and passing in parameters. This is an improvement for the original ThreadStart delegate.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.