BackgroundWorker Implementing multithreaded Operations

Source: Internet
Author: User
Tags response code

Background introduction:

in the process of doing the procedure, we are likely to encounter this situation: when we perform a relatively time-consuming operation, that is, the interface load data is slightly larger, when the operation is not completed before the operation of the interface, there will be a stop response situation, which is called the interface suspended animation state, that a small circle to turn, It must be a headache for everyone to look at. This is, of course, a place that has a great impact on user experience.

How to make a timely response to the user interface? Multithreaded operations.

Introducing the BackgroundWorker component:

BackgroundWorker is the control used to perform multithreaded tasks in NET, which allows programmers to perform some operations on a separate thread.

Common methods

1.RunWorkerAsync begins a background operation. Raising the DoWork event

2.CancelAsync request to cancel a pending background operation.

Note: This method is to set the Cancellationpending property to True and does not terminate the background operation. In the background operation, check the Cancellationpending property to determine whether you want to continue the time-consuming operation.

3.ReportProgress raises the ProgressChanged event.

Common Properties

1.CancellationPending Indicates whether the application has requested cancellation of the background operation. the read-only property, which defaults to False, evaluates to True when the CancelAsync method is executed.

2.WorkerSupportsCancellation Indicates whether asynchronous cancellation is supported. To execute the CancelAsync method, you need to set the property to true first.

3.WorkerReportsProgress Indicates if progress can be reported. To execute the ReportProgress method, you need to set the property to true first.

Common events

1.DoWork occurs when the RunWorkerAsync method is called.

occurs when a 2.RunWorkerCompleted background operation is completed, canceled, or an exception is thrown.

3.ProgressChanged occurs when the ReportProgress method is called.

Note: No user interface objects are manipulated in the DoWork event handler. Instead, you should communicate with the user interface through the progresschanged and runworkercompleted events.

If you want to communicate with the control of the user interface in the DoWork event handler, you can use the ReportProgress method. reportprogress (int percentprogress, Object userState), which can pass an object.

The ProgressChanged event can get this information object from the Userstate property of the parameter ProgressChangedEventArgs class. This event also enables the progress bar function to present the progress of the task to the user in real time.

Simple program with BackgroundWorker more convenient than thread, thread and control communication on the user interface is more troublesome, need to use a delegate to invoke the control's invoke or BeginInvoke method, no BackgroundWorker convenient.

BackgroundWorker Demo

namespace backgroundworkertest{public partial class Form1:form {public Form1 () {Initia            Lizecomponent (); backgroundworker1.workerreportsprogress = true;//Report Completion Progress backgroundworker1.workersupportscancellation = true;// Allow user to terminate background thread}//Start button private void Button1_Click (object sender, EventArgs e) {if (!ba                CKGROUNDWORKER1.ISBUSY)//Determine if BackgroundWorker1 is running asynchronous operation {//backgroundworker1.runworkerasync (); Backgroundworker1.runworkerasync (1000);//start background operation, call DoWork event}}//dowork Event Declares a time-consuming operation to be performed private void Backgroundworker1_dowork (object sender, DoWorkEventArgs e) {e.result = L Istnumber (BackgroundWorker1, E);//The result of the operation is saved in E. Result} bool Listnumber (object sender, DoWorkEventArgs e) {int num= (int) e.argument;//           Accept incoming parameters for (int i = 1; I <= num; i++) {     if (backgroundworker1.cancellationpending)//Determine if the cancellation of the background operation is requested {e.cancel=true;                return false;                }//backgroundworker1.reportprogress (i * 100/num);            Backgroundworker1.reportprogress (i * 100/num,i);//Report Completion Progress Thread.Sleep (0);//Background thread hand over time slice}        return true; private void Backgroundworker1_progresschanged (object sender, ProgressChangedEventArgs e) {//            Pass the completion progress data to the progress bar progressbar1.value = E.progresspercentage; Label1.            Text = e.progresspercentage + "%";        Displays the results of the intermediate calculations in the ListBox control LISTBOX1.ITEMS.ADD (E.userstate); Private void Backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {if (  !e.cancelled && e.error==null) {MessageBox.Show ("is the processing done?          "+ E.result);   } else//If the background thread is canceled or an exception has occurred {           MessageBox.Show ("Did you finish the process?")          False "); }}//Cancel button private void Button2_Click (object sender, EventArgs e) {if (Backgroundwo Rker1. Workersupportscancellation==true) {backgroundworker1.cancelasync ();//Cancel background operation back Groundworker1.dispose ();//Release Resources}}}}

Summarize:

Use BackgroundWorker the approximate steps to achieve multithreading are:

1 , binding threads, setting properties

2 , call BackgroundWorker runworkerasync ( can pass parameters ) dowork events

3 , Statement DoWork Events delegate method that performs time-consuming operations in the background

4 , in time-consuming operations, judging cancellationpending property, if the false then Exit

5 backgroundworker reportprogress method, which will invoke the progresschanged event ( can be changed through object )

6 The response code of the event will be changed to the user

7 , if you need to cancel the time-consuming operation, call the BackgroundWorker of the CancelAsync methods, needs and steps 3 used together

in general , it is BackgroundWorker component to create a new thread and put the time-consuming parts into this thread for processing in the background. This will not affect the normal use of the interface. As a popular example, when we open a Web page, the text is loaded, and the image is slowly appearing. This is the application of the thread, the Web page opens the first time to render the text, for users to browse, and then put the loading picture into a separate thread, asynchronously executed in the background, after the completion of the picture rendered.

This avoids an open interface to load a lot of information, and the resulting interface suspended animation state, greatly improve the user experience.

Thread processing this piece is not ripe, hope everybody pointing.


BackgroundWorker Implementing multithreaded Operations

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.