Use of C # BackgroundWorker

Source: Internet
Author: User

Article excerpt from: http://www.cnblogs.com/tom-tong/archive/2012/02/22/2363965.html

BackgroundWorker can be used to start a background thread.

Main Events and Parameters:
1.dowork--This event is triggered when the Backgroundworker.runworkerasync method is executed, and the DoWorkEventArgs parameter is passed;

2.runworkercompleted--The event is triggered when an asynchronous operation completes or terminates halfway.

If you need to terminate the background operation prematurely, you can call the Backgroundworker.cancelasync method.

Detects if the Backgroundworker.cancellationpending property is true in the function that handles the DoWork event, and if true, indicates that the user has canceled the asynchronous call while setting the Doworkeventargs.cancel property to True (passed to the second parameter of the function that handles the DoWork event) so that when exiting an asynchronous call, you can let the function that handles the RunWorkerCompleted event know whether to exit normally or in the middle.
3.progresschanged--the processing state change obtained in the operation processing, triggering the event through the backgroundworker.reportprogress (int) method, and passing the ProgressChangedEventArgs, It contains the percentage of processing, which sets the ProgressBar control on the UI interface.


The Main method:
1. The backgroundworker.runworkerasync--"Start" Asynchronous call method has two overloads RunWorkerAsync (), RunWorkerAsync (object argument), The second overload provides a parameter that can be used by an asynchronous invocation. (If you have more than one parameter to pass, use a class to pass them on). Calling the method triggers the DoWork event and passes the Doworkeventarg parameter for the function that handles the DoWork event, which contains the parameters passed by the RunWorkerAsync. Specific complex operations can be done in the corresponding dowork processing functions.
2. backgroundworker.reportprogress--needs to constantly feed back the progress to the user in a lengthy operation, so that it can call the reportprogress (int percent), in the call reportprogress method, the ProgressChanged event is triggered. Provides an integer between 0 and 100 that represents the percentage of background activity that has completed. You can also provide any object as a second parameter, allowing you to pass state information to the event handler. As the ProgressChangedEventArgs parameter property passed to this procedure, the percentage and your own object (if provided) are passed to the ProgressChanged event handler. These properties are named Progresspercentage and UserState respectively, and your event handlers can use them in any way they want. (Note: The method is only available if the Backgroundworker.workerreportsprogress property is set to true).
3. backgroundworker.cancelasync--This method is called when the asynchronous call needs to be exited. However, this is not enough because it simply sets the Backgroudworker.cancellationpending property to True. You need to constantly check whether backgroudworker.cancellationpending is true if it is true or quit when the specific asynchronous call is processed. (Note: The method is only available if the Backgroundworker.workersupportscancellation property is set to true).




BackgroundWorker components
The BackgroundWorker component was added to the VS2005, which is very convenient to use in multithreaded programming, but at the beginning it took a lot of detours because it was not clear about its use mechanism, and now I would like to share with you the experience of using it.
This column of properties, methods, and events are primarily used in the BackgroundWorker class:
Important attributes:
1. Cancellationpending gets a value indicating whether the application has requested to cancel the background operation. By judging the Cancellationpending property in the DoWork event, you can determine whether you need to cancel the background operation (that is, the end thread);
2. IsBusy gets a value indicating whether the BackgroundWorker is running an asynchronous operation. Use the IsBusy property in the program to determine whether the background operation is in use;
3, Workerreportsprogress Gets or sets a value that indicates whether BackgroundWorker can report progress updates
4, Workersupportscancellation Gets or sets a value that indicates whether BackgroundWorker supports asynchronous cancellation. Setting Workersupportscancellation to True allows a program to invoke the CancelAsync method to submit a request to terminate a pending background operation;
Important methods:
1. CancelAsync request to cancel a pending background operation
2, RunWorkerAsync start to perform background operations
3, ReportProgress trigger ProgressChanged Event
Important Events:
1. Occurs when DoWork calls RunWorkerAsync
2. Occurs when ProgressChanged calls ReportProgress
3. runworkercompleted occurs when a background operation is completed, canceled, or an exception is thrown
Another three important parameters are Runworkercompletedeventargs and DoWorkEventArgs, ProgressChangedEventArgs.
BackgroundWorker properties, methods, invocation mechanism and order of the events:

There are 3 important parameter transfer processes that are visible throughout the life cycle:
Parameter Pass 1: This time the parameter pass is to pass an object in RunWorkerAsync (object) to the doworkeventargs.argument of the DoWork event, because here only one argument can be passed, So in the actual application to encapsulate a class, the entire instantiated class as a RunWorkerAsync object is passed to the doworkeventargs.argument;
Parameter Passing 2: This is to pass the program running progress to the ProgressChanged event, the actual use of the method and events are often used to update the progress bar or log information;
Parameter Pass 3: Before the DoWork event ends, Assigns the result data produced by the background thread to the Doworkeventargs.result side to get the results from the background thread by invoking the Runworkercompletedeventargs.result property in the RunWorkerCompleted event.
In addition, you can see that the DoWork event is running in a background thread, so you cannot manipulate the contents of the user interface in this event, and you can use the ProgressChanged event and the runworkcompleted event if you need to update the user interface.


In the WinForm often encountered some time-consuming interface, such as statistics on a disk partition folder or the number of files, if the partition is large or too many files, processing is not good will cause "suspended animation" situation, or reported "invalid between threads" exception, in order to solve this problem, you can use the delegate to handle, You can also use the BackgroundWorker class in. net2.0.

The BackgroundWorker class is a newly added class in. NET 2.0 that can be used for long-time operations that do not require long waits for the user.
Note Make sure that 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.
 Public Partial classMainwindow:window {PrivateBackgroundWorker M_backgroundworker;//Declare background objects          PublicMainWindow () {InitializeComponent (); M_backgroundworker=NewBackgroundWorker ();//instantiating a Background objectm_backgroundworker.workerreportsprogress=true;//setting to advertise progressM_backgroundworker.workersupportscancellation =true;//settings can be canceledm_backgroundworker.dowork+=NewDoworkeventhandler (DoWork); M_backgroundworker.progresschanged+=NewProgresschangedeventhandler (updateprogress); M_backgroundworker.runworkercompleted+=NewRunworkercompletedeventhandler (completedwork); M_backgroundworker.runworkerasync ( This); }          voidDoWork (Objectsender, DoWorkEventArgs e) {BackgroundWorker BW= Sender asBackgroundWorker; MainWindow win= E.argument asMainWindow; inti =0;  while(I <= - )            {                if(BW. cancellationpending) {E.cancel=true;  Break; } bw. ReportProgress (i++); Thread.Sleep ( +); }        }         voidUpdateProgress (Objectsender, ProgressChangedEventArgs e) {            intProgress =E.progresspercentage; Label1. Content=string. Format ("{0}", progress); }          voidCompletedwork (Objectsender, Runworkercompletedeventargs e) {            if(E.error! =NULL) {MessageBox.Show ("Error"); }            Else if(e.cancelled) {MessageBox.Show ("Canceled"); }            Else{MessageBox.Show ("completed"); }        }          Private voidButton1_Click (Objectsender, RoutedEventArgs e)        {M_backgroundworker.cancelasync (); }    }

Use of C # BackgroundWorker

Related Article

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.