C # backgroundworker--start a background thread

Source: Internet
Author: User
1, the main events and parameters:

(1) dowork--The event is triggered when the Backgroundworker.runworkerasync method is executed, and the DoWorkEventArgs parameters are passed;

(2) The runworkercompleted--asynchronous operation completes or terminates midway will trigger the event.

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

Detects whether 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 the asynchronous call is exited, the function that handles the RunWorkerCompleted event knows whether to exit normally or midway out.
(3) The processing state change obtained in the progresschanged--operation processing, the event is triggered by the backgroundworker.reportprogress (int) method, and the ProgressChangedEventArgs is passed, It contains a percentage of the processing, which sets the ProgressBar control on the UI interface.
2. The main approach:

The

(1) backgroundworker.runworkerasync--"Start" asynchronous invocation 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). Calling this method triggers the DoWork event and passes the Doworkeventarg parameter for the function that handles the DoWork event, which contains the parameters that the RunWorkerAsync passes. In the corresponding DoWork processing function can do the specific complex operation.
(2) backgroundworker.reportprogress--needs to keep feedback to the user in a lengthy operation so that the reportprogress (int percent) can be invoked When the ReportProgress method is used, the ProgressChanged event is triggered. Provides an integer between 0 and 100 that represents the percentage of background activity that has been completed. You can also provide any object as the second parameter that allows you to pass state information to an event handler. As a ProgressChangedEventArgs parameter property passed to this procedure, the percentages and your own objects (if provided) are passed to the ProgressChanged event handler. These attributes are named Progresspercentage and UserState respectively, and your event handlers can use them in any way you want. (Note: This method is only available if the Backgroundworker.workerreportsprogress property is set to true).
(3) This method is invoked when a backgroundworker.cancelasync--is required to exit an asynchronous call. But the sample is not enough, because it simply sets the Backgroudworker.cancellationpending property to True. You need to check whether the backgroudworker.cancellationpending is true when the specific asynchronous call is processed, and then quit if it is true. (Note: This method is only available if the Backgroundworker.workersupportscancellation property is set to true). 3.BackgroundWorker Components

The BackgroundWorker component was added to the VS2005, which is handy for multithreaded programming, but in the beginning it took a lot of detours by not knowing how it was used, and now share my experience in 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 cancellation of the background operation. By judging the cancellationpending attribute 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 if 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 indicating whether BackgroundWorker supports asynchronous cancellation. Setting Workersupportscancellation to True allows a program to call a CancelAsync method to commit a request to terminate a pending background operation;
Important Method:
1, CancelAsync request to cancel the pending background operation
2, RunWorkerAsync began to perform background operations
3. ReportProgress raises progresschanged Event
Important Events:
1. Occurs when DoWork calls RunWorkerAsync
2. Occurs when ProgressChanged calls ReportProgress
3. runworkercompleted occurs when the background operation is completed, canceled, or an exception is thrown
Another three important parameters are Runworkercompletedeventargs and DoWorkEventArgs, ProgressChangedEventArgs.4. BackgroundWorker of the various properties, methods, events and the order of the call:

The above diagram shows that 3 important parameter transfer processes occur throughout the life cycle:
Parameter Pass 1: This parameter pass is to pass the object in RunWorkerAsync (object) to the doworkeventargs.argument of the DoWork event, since only one parameter can be passed here. So in the practical application to encapsulate a class, the whole instantiated class is passed to the Doworkeventargs.argument as RunWorkerAsync object;
Parameter Pass 2: This is to pass the program running progress to the ProgressChanged event, the actual use often use to the method and event update progress bar or log information;
Parameter Pass 3: Before the end of the DoWork event, Assigns the result data produced by the background thread to the Doworkeventargs.result side of the RunWorkerCompleted event to invoke the Runworkercompletedeventargs.result property to get the result of the background thread.
In addition, you can see from the image above that the DoWork event is running in a background thread, so the contents of the user interface cannot be manipulated in the event, and if the user interface needs to be updated, the ProgressChanged event and runworkcompleted event can be used to implement it.

    in WinForm often encountered a number of time-consuming operating interface, such as statistics on a disk partition folder or the number of files, if the partition is very large or too many files, the handling of bad will cause "suspended animation", or reported "the operation of the thread is invalid" exception, in order to solve this problem, you can use the delegate to handle, in the. net2.0 can also use the BackgroundWorker class. The

    BackgroundWorker class is a newly added class in. NET 2.0 that can be used for long periods of time without requiring a user to wait for a long time.
Note that you are sure that no user interface objects are being manipulated in the DoWork event handler. Instead, you should communicate with the user interface through the progresschanged and runworkercompleted events.

Public partial class Mainwindow:window {private BackgroundWorker m_backgroundworker;//declare background object P
 
            Ublic MainWindow () {InitializeComponent (); M_backgroundworker = new BackgroundWorker (); Materialized Background Object m_backgroundworker.workerreportsprogress = true; Setting can advertise progress m_backgroundworker.workersupportscancellation = true;
            Setting can cancel M_backgroundworker.dowork + = new Doworkeventhandler (DoWork);
            M_backgroundworker.progresschanged + = new Progresschangedeventhandler (updateprogress);
 
            m_backgroundworker.runworkercompleted + = new Runworkercompletedeventhandler (completedwork);
        M_backgroundworker.runworkerasync (this); } void DoWork (object sender, DoWorkEventArgs e) {BackgroundWorker bw = sender as Backgrou
            Ndworker;
 
            MainWindow win = e.argument as MainWindow;
            int i = 0;
      while (I <= 100)      {if (BW).
                    cancellationpending) {E.cancel = true;
                Break } bw.
     
                ReportProgress (i++);
 
            Thread.Sleep (1000); } void UpdateProgress (object sender, ProgressChangedEventArgs e) {int progress =
 
            E.progresspercentage; Label1. Content = string.
        Format ("{0}", progress); 
            } void Completedwork (object sender, Runworkercompletedeventargs e) {if (E.error!= null)
            {MessageBox.Show ("Error");
            else if (e.cancelled) {MessageBox.Show ("Canceled");
            else {MessageBox.Show ("Completed"); }} private void Button1_Click (object sender, RoutedEventArgs e) {M_backgroundwor Ker.
      CancelAsync ();  }
    } 

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




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.