Use of the backgroundworker class in event-based asynchronous mode

Source: Internet
Author: User

To perform time-consuming operations in the background, create a backgroundworker to listen on events that report the operation progress and send signals when the operation is complete.

Here we use an example in C # advanced programming to illustrate the use of this class:

 Using System; Using System. Collections. Generic; Using System. componentmodel; Using System. Data; Using System. drawing; Using System. LINQ; Using System. text; Using System. Windows. forms; Using System. Threading; Namespace Eventasync { Public  Partial   Class Frmbackgroundworker: FORM { Public Frmbackgroundworker () {initializecomponent ();} Private   Void Btncal_click ( Object Sender, eventargs e ){ This . Btncal. Enabled = False ; This . Txtresult. Text = string. empty; This . Btncancel. Enabled = True ; This . Prosbarcal. value = 0; bgworkercal. runworkerasync ( New Calcinput ( Int . Parse ( This . Txtx. Text ), Int . Parse ( This . Txty. Text )));} Private   Void Ondowork ( Object Sender, doworkeventargs e) {calcinput input = (calcinput) E. argument; For ( Int I = 0; I <10; I ++) {thread. Sleep (5000); bgworkercal. reportprogress (I * 10 );If (Bgworkercal. cancellationpending) {e. Cancel = True ; Return ;}} E. Result = input. x + input. Y ;} Private   Void Onworkcompleted ( Object Sender, runworkercompletedeventargs e ){ If (E. cancelled ){ This . Txtresult. Text = "Cancelled" ;} Else {This . Txtresult. Text = E. Result. tostring ();} This . Btncal. Enabled = True ; This . Btncancel. Enabled = False ; This . Prosbarcal. value = 100 ;} Private   Void Frmbackgroundworker_load ( Object Sender, eventargs e ){} Private   Void Btncancel_click ( Object Sender, eventargs e) {bgworkercal. cancelasync ();} Private   Void Onprogresschanged ( Object Sender, progresschangedeventargs e ){ This . Prosbarcal. value = E. progresspercentage ;}}}

In this example:

Add a backgroundworker class to Windows formProgramMedium

The backgroundworker class has the following attributes and methods:

Attribute:

Name

Generatemember: True is not commonly used.

Modifiers private does not need to be changed.

Workerreportsprogress: The default value is false. If you require the backgroundworker class report SS progress in the program, set it to true. in this program, we need to use the backgroundworker class to return the progress to the progress bar, so set it to true

Workersuppscanscancellation: The default value is false. In this program, we need to enable the cancellation function, so set it to true.

 

Method:

Dowork

Progresschanged

Runworkercompleted

The three methods are combined with examples.

Here, we specify the three methods of the backgroundworker class respectively.

Dowork: ondowork

  private   void  ondowork ( Object  sender, doworkeventargs e) {calcinput input = (calcinput) E. argument;  for  ( int  I = 0; I <10; I ++) {thread. sleep (5000); bgworkercal. reportprogress (I * 10);  If  (bgworkercal. cancellationpending) {e. cancel =  true ;  return ;}} E. result = input. X + input. Y ;}

Read this sectionCodeYou will know.

The dowork method refers to what the backgroundworker class needs to do during running. The corresponding entry should be

Bgworkercal. runworkerasync (New calcinput(int.parse(this.txt X. Text), int.parse(this.txt Y. Text )));

That is, the order:

Backgroundworker calls the runworkerasync method ------> execute the dowork method of the backgroundworker class ----------> execute the progresschanged method during progress update -------------> execute the runworkercompleted method when the progress is completed or canceled

 

In the onwork event ondowork, backgroundworker does the following:

A. Main programs, such as reading data or something

B. Feedback Progress bgworkercal. reportprogress (I * 10 );

C. Process cancel. If the bgworkercal. cancelasync () event is triggered during dowork, perform corresponding processing.

If (bgworkercal. cancellationpending)
{
E. Cancel = true;
Return;
}

The cancellationpending attribute indicates whether the backgroundworker class receives the cancelasync event.

 

In the event onprogresschanged corresponding to progresschanged, backgroundworker does the following:

A. reflect the progress to the progress bar

 

In the onworkcompleted event corresponding to runworkercompleted, backgroundworker does the following:

A. If the user cancel is displayed, the corresponding result is displayed.

B. If the user does not have cancel, the success result is displayed.

C. Set the progress to the completion mark

 

Other examples are further analyzed.

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.