C # multithreading 1,

Source: Internet
Author: User

In your spare time, consider how to improve the system software system performance, especially winProgramIn addition to object lifecycle management, I thought of using multiple threads, opened a book, and wrote my learning process here.

As we all know, in Development Win, the form control is created in a thread, So If multithreading is used in the program, you cannot directly process the control in a non-creation control thread. You can only process the control through invoke (), begininvoke (), endinvoke (), and The invokerequired attribute, therefore, delegates can be used for implementation, but the backgroundworker class is provided in win event-based development. It encapsulates the processing and access process of the thread throughout its lifecycle, it was quite troublesome at first, but it was quite clear to take a closer look at the handling process. Below we will illustrate this method through a small example.

Before using the backgroundworker class, first let's talk about the following aspects of the life cycle of a new thread (in your own words). First, initialize this thread, in the class, dowork () events are triggered by calling the runworkerasync () method. Of course, values can be passed. After the thread is started, if you want to make the thread work properly, make sure that the workerreportsprogress attribute is true, so that you can use the progresschanged () event normally, the runworkercompleted () event is triggered when the thread finishes processing or is interrupted. You can directly access the Form Control (which saves a lot of time) in the two processing methods. The thread is interrupted, to provide this function, ensure that the workersuppscanscancellation attribute is true. If the cancelasync () method is triggered, the thread can be interrupted. Of course, after the thread is interrupted, runworkercompleted () is also called () method. The following is an example. The interface is as follows:

In this example, a progress bar (vulgar, easy to understand) is processed. When you click the start button, the progress bar displays the progress bar. At this time, the start button becomes unavailable. When the slow processing process (the progress bar here) ends, the result of adding the text (numbers) in the two file boxes will be displayed in lable1. When you click the cancel button during processing, the thread will stop and lable1 will be displayed as "Abort.

Because it is an object in the process of passing values, a simple structure type is implemented to encapsulate the required data (here two texts are used), which is as follows:

1 Public   Struct Input
2 {
3 Public   Int X;
4 Public   Int Y;
5
6 Public Input ( Int X, Int Y)
7 {
8This. X=X;
9This. Y=Y;
10}
11 }

 

Check the event processing of the Start button. This will trigger the thread to enable the event dowork ().CodeAs follows:

 

1 Private   Void Button#click ( Object Sender, eventargs E)
2 {
3 This . Button1.enabled =   False ;
4 This . Progressbar1.value =   0 ;
5 Backgroundworker1.runworkerasync (
6 New Input ( Int . Parse (textbox1.text ), Int . Parse (textbox2.text )));
7 }

 

The buttons and progress bar status are controlled here, and the parameter-based overload method runworkerasync (object target) is implemented to pass the above structure to the thread. The dowork () method of the event is triggered. The event processing code is as follows:

 

1 Private   Void Backgroundworkerincludowork ( Object Sender, doworkeventargs E)
2 {
3 Input put = (Input) E. argument;
4 For ( Int I =   0 ; I <=   9 ; I ++ )
5 {
6 Thread. Sleep ( 1000 );
7 Backgroundworker1.reportprogress (I *   10 );
8 If (Backgroundworker1.cancellationpending)
9 {
10E. Cancel= True;
11Return;
12}
13 }
14 E. Result = Put. x + Put. Y;
15 }

 

You can see that the method parameters can be obtained through E. argument and converted to the type. In this method body, the main work to be done by the thread is processed. You can see that backgroundworker1.reportprogress (I* 10);This method is called to trigger progress bar update. The attribute workerreportsprogress is true, which is the prerequisite for this. The Code is as follows:

 

1 Private   Void Backgroundworker1_progresschanged ( Object Sender, progresschangedeventargs E)
2 {
3This. Progressbar1.value=E. progresspercentage;
4}

 

In this method, the progress bar status is set.

In the preceding main method, the backgroundworker1.cancellationpending attribute is determined to identify the thread state. Once the thread is interrupted, the cancel attribute is set to true and the processing is completed, I think this is very important! After the thread completes processing, it can set a value for the result attribute of the object type, that is, providing parameters for the runworkercompleted () method. This method is triggered when the thread ends (automatically or manually triggered). The final processing of program data and forms can be performed here. The Code is as follows.

 

1   Private   Void Backgroundworkerappsrunworkercompleted ( Object Sender, runworkercompletedeventargs E)
2 {
3 If (E. cancelled)
4 {
5 This . Lable1.text =   " Canceled " ;
6 This . Progressbar1.value =   0 ;
7 }
8 Else
9 {
10 This . Lable1.text = E. Result. tostring ();
11 This . Progressbar1.value =   100 ;
12 }
13
14 This . Button1.enabled =   True ;
15 }

The status of the event is determined. If the event ends normally, the final state is displayed. If the event is interrupted, the event is canceled.

The small example is over. The biggest benefit is that you don't have to worry too much about the aftermath and the whole process. All three main methods are done.

At the beginning, I started to contact win. If there is something missing, please give me more advice!

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.