Thread Family 10, no need to explicitly call the threading scenario

Source: Internet
Author: User

In general, we will create threads and use threads first through the thread's constructor. And in fact,. NET is a method that is provided by some classes and is internally processed using multithreading. Some classes that encapsulate multithreaded, asynchronous processing methods conform to the event-driven asynchronous Pattern (event-based Asynchronous Pattern). For the BackgroundWorker class under System.ComponentModel, this class conforms to this pattern.

BackgroundWorker Class Properties:
Workersupportscancellation: Set to True to allow cancellation
Workerreportprogress: Set to True indicates progress can be displayed

BackgroundWorker class Event:
DoWork: What the background thread is going to do
ProgressChanged: Progress Trigger Event
RunWorkerCompleted: Triggers when progress ends, throws an exception, or cancels execution

For example, use the BackgroundWorker class in a Windows Forms application.

→ Create a new Windows Forms application that includes 2 button,1 label,1 progressbar,1 backgournworker controls.

→ Set the Workersupportscancellation property of the Backgournworker control and workerreportprogress to true.

→ Background Code is:

       Private void backgroundworker1_dowork (object sender, DoWorkEventArgs e)
        {
            int sum = 0;
             for (int i = 1; I <=100; i++)
            {
                Thread.Sleep (1000);
                sum = sum + 1;
                Backgroundworker1.reportprogress (i);
                If you cancel the calculation
                if (backgroundworker1.cancellationpending)
                {
                    true;
                    Backgroundworker1.reportprogress (0);
                    return;
                }
                E.result = sum;
            }
        }
        Private void backgroundworker1_progresschanged (object sender, ProgressChangedEventArgs e)
        {
            Bring the BackgroundWorker process to the ProgressBar.
            progressBar1.Value = E.progresspercentage;
            Put the BackgroundWorker process on the label
            Label1. Text = e.progresspercentage + "%";
        }
        Private void backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e)
        {
            if //May end in a canceled manner
            {
                Label1. Text = " calculation is canceled ";
            }
            Else if null) //May end in a way that throws an exception
            {
                Label1. Text = E.error.message;
            }
            Else //May end normally
            {
                Label1. Text = "1 to 100 and for:" + e.result.tostring ();
            }
        }
        Start calculation
        Private void Btncalculate_click (object sender, EventArgs e)
        {
            if (!backgroundworker1.isbusy)
            {
                Backgroundworker1.runworkerasync ();
            }
        }
        Cancel Calculation
        Private void Btncancel_click (object sender, EventArgs e)
        {
            if (backgroundworker1.isbusy)
            {
                Backgroundworker1.cancelasync ();
            }
            
        }

In the DoWork event:
0BackgroundWorker instance method reportprogress, which is used to display the progress of background threads to the progress bar.
0 Save the DoWork calculation to the result property of the DoWorkEventArgs type

In the ProgressChanged event:
0 The Progresspercentage property values for the ProgressChangedEventArgs type parameter of the event are displayed respectively to the progress bar and the label

In the RunWorkerCompleted event:
0 The Cancelled property value of the Runworkercompletedeventargs type parameter of the event is used to determine whether to cancel
The error property value of the 0RunWorkerCompletedEventArgs type parameter is used to record the exception
The result property value of the 0RunWorkerCompletedEventArgs type parameter is taken out in the DoWork event, the value set for the result property of the DoWorkEventArgs type


Click the "Start Calculation" button and the background thread runs and displays on the progress bar and label.

The Thread family includes:

Thread series 01, foreground thread, background thread, thread synchronization thread series 02, multiple threads simultaneously handle a lengthy task to save time thread series 03, multithreading shared data, multithreading does not share data

Thread Series 04, passing data to threads, thread naming, thread exception handling, threads pool thread family 05, manually ending thread thread family 06, viewing the thread pool and its thread thread family 07 through CLR code, Use the lock statement block or the interlocked type method to guarantee the data synchronization thread series 08 for the self-increment variable, to implement the various ways of the thread lock, to use Lock,montor,mutex,semaphore and thread deadlock

Thread series 09, thread waits, notifications, and manual control of the number of threads

Thread Family 10, no need to explicitly call the threading scenario

Thread Family 10, no need to explicitly call the threading scenario

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.