Multi-thread backgroundworker component

Source: Internet
Author: User
Multi-thread backgroundworker components 2010-06-25 from: Sina Blog font size: [large, small]
    • Abstract:The backgroundworker component is very convenient to use in multi-threaded programming. However, at the beginning, it took a lot of detours because it did not understand its usage mechanism, now I will share with you my experience in using it.

Backgroundworker component

Added the backgroundworker component in vs2005, which is very convenient to use in multi-threaded programming. However, at the beginning, it took a lot of detours because it was not clear about its usage mechanism, now I will share with you my experience in using it.
 

This attribute, method, and event are mainly used in the backgroundworker class:
Important attributes:
1. cancellationpending gets a value indicating the application Program Whether the background operation has been canceled. By judging the cancellationpending attribute in the dowork event, you can determine whether the background operation needs to be canceled (that is, the end thread );
2. isbusy gets a value indicating whether the backgroundworker is running an asynchronous operation. The isbusy attribute is used in the program to determine whether background operations are in use;
3. workerreportsprogress gets or sets a value that indicates whether the backgroundworker can report progress updates.
4. workersuppscanscancellation gets or sets a value that indicates whether backgroundworker supports asynchronous cancellation. Set workersuppscanscancellation to true so that the program can call the cancelasync method to submit a request to terminate the suspended background operation;
Important methods:
1. cancelasync requests to cancel pending background operations
2. runworkerasync starts to perform background operations.
3. reportprogress raises the progresschanged event.
Important events:
1. occurs when dowork calls runworkerasync.
2. progresschanged when reportprogress is called
3. runworkercompleted occurs when the background operation is completed, canceled, or exception is thrown.
There are also three important parameters: runworkercompletedeventargs, doworkeventargs, and progresschangedeventargs.
The Calling mechanism and sequence of attributes, methods, and events of backgroundworker:

It can be seen that three important parameter transfer processes occurred throughout the life cycle:
Parameter Pass 1: This Parameter Pass is to pass the object in runworkerasync (object)
Doworkeventargs. argument of the dowork event. Because only one parameter can be passed here, the actual application encapsulates a class and instantiates the entire class.
The object as runworkerasync is passed to doworkeventargs. argument;
Parameter transfer 2: This is to pass the program running progress to the progresschanged event. In actual use, it is often used to update the progress bar or log information for methods and events;
Parameter Pass 3: grant the result data generated by the background thread
Doworkeventargs. result is called in the runworkercompleted event
The runworkercompletedeventargs. Result attribute gets the result generated by the background thread.
In addition, we can see that the dowork event is run in the background thread, so the user interface content cannot be operated in this event. If you need to update the user interface, you can use the progresschanged event and runworkcompleted event.

Winform often encounters some time-consuming operation interfaces, such as counting the number of folders or files in a disk partition. If the partition is large or the number of files is too large, the processing will lead to a "false death"
Or an exception of "invalid inter-thread operation" is reported. To solve this problem, you can use a delegate to handle it. In. net2.0, you can also use the backgroundworker class.

The backgroundworker class is a newly added class in. NET 2.0. This class can be used when long operations are required without long waits.
Make sure that no user interface objects are operated in the dowork event handler. You should use the progresschanged and runworkercompleted events to communicate with the user interface.UsingSystem;

UsingSystem. Collections. Generic;

UsingSystem. componentmodel;

UsingSystem. Data;

UsingSystem. drawing;

UsingSystem. text;

UsingSystem. Windows. forms;

Namespace Backgroundworkerdemo

{

Public Partial Class Mainform: Form

{

Private Backgroundworker worker = New Backgroundworker ();

Public Mainform ()

{

Initializecomponent ();

Worker. workerreportsprogress = True ;

Worker. workersuppscanscancellation = True ;

// Where to officially do things

Worker. dowork + = New Doworkeventhandler (dowork );

// What to do when the task is called, such as prompts

Worker. progresschanged + = New Progresschangedeventhandler (progesschanged );

// Report progress when the task is in progress

Worker. runworkercompleted + = New Runworkercompletedeventhandler (completework );

}

// Runworkerasync is called.

Public Void Dowork ( Object Sender, doworkeventargs E)

{

E. Result = Computefibonacci (worker, e ); // When computefibonacci (worker, e) returns, the asynchronous process ends.

}

// An error occurred while calling reportprogress.

Public Void Progesschanged ( Object Sender, progresschangedeventargs E)

{

This . Progressbar1.value = E. progresspercentage;

}

// This error occurs when the background operation is completed, canceled, or causes an exception.

Public Void Completework ( Object Sender, runworkercompletedeventargs E)

{

MessageBox. Show ( " Done! " );

}

Private Int Computefibonacci ( Object Sender, doworkeventargs E)

{

For ( Int I = 0 ; I < 1000 ; I ++ )

{

If (Worker. cancellationpending)

{

E. Cancel = True ;

}

Else

{

Worker. reportprogress (I );

}

System. Threading. thread. Sleep ( 10 );

}

Return - 1 ;

}

PrivateVoidBtnstart_click (ObjectSender, eventargs E)

{

Worker. runworkerasync ();

Btnstart. Enabled=False;

Btnpause. Enabled=True;

}

private void btnpause_click ( Object sender, eventargs e)

{< br>
btnpause. enabled = false ;< br>
btnstart. enabled = true ;< br>
worker. cancelasync ();

} if you do not want to call the main program, load:
system. windows. forms. form. checkforillegalcrossthreadcils = false;

    • Personal Data
    • My releases
    • Message
    • Friend
    • Favorites
    • Create a topic
    • Write blog
C # Explanation and use of the concept of backgroundworker Code Implementation

Affiliated to: It> language basics> Well C

Topic description Title: explanation of the concept of backgroundworker in C # And code implementation [Creator] [Appreciated] 0 times [Browsed] 112 times [QuestionArticle] 1 [Comments under question] 0 Best article One at the top Loading the article list... Loading the article list... Reading author information ... [Appreciated] 1 time [Browsed] Once [Comment] 0 [Challenged] n times [Date]

Sub-title: Use of backgroundworker
Reprinted Information:
Http://blog.csdn.net/rrrrssss00/article/details/7707678

A program requires a large number of operations and must support user interaction during the operation. In order to get a better user experience, backgroundworker is used to complete this function.

  Basic operations: Bgw.Runworkerasync (): Start running in the background, This function then triggers the bgw. doworker event, and the operations to be executed are written in the doworker Event Response Function, You can also add a parameter to this function. The parameter is obtained from E. arguement of the doworker event processing function.   Bgw.Cancelasync (): Application background program stops, Note that this function cannot actually stop the background program, and only the bgwCancellationpendingIf the value is set to true, You need to determine this value in the program running in the background, and then stop running the background program. Note that before using this methodWorkersuppscanscancellationSet the value to true, otherwise it will not work.   Bgw.Reportprogress (): Call in the background program and send progress information to the main thread, One or two parameters can be included, and one is an int-type progress (0 ~ 100). A parameter of the custom type can transmit any information. After the bgw is called, bgw is triggered. progresschanged event, you can write the code of the interface change in the event response function, the two parameters mentioned earlier can be from bgw. obtained from parameter E of the progresschanged event response function, which is E.Progresspercentage andE. userstate. Note that before using this methodThe workerreportsprogress value is set to true, otherwise the event will not be triggered.

Start background running:
  1. Bgw =NewBackgroundworker ();
  2. Bgw. workersuppscanscancellation =True;
  3. Bgw. workerreportsprogress =True;
  4. Bgw. dowork + =NewDoworkeventhandler (bgw_dowork );
  5. Bgw. progresschanged + =NewProgresschangedeventhandler (bgw_progresschanged );
  6. Bgw. runworkercompleted + =NewRunworkercompletedeventhandler (bgw_runworkercompleted );
  7. Bgw. runworkerasync ();

Dowork event processing functions:

    1. VoidBgw_dowork (ObjectSender, doworkeventargs E)
    2. {
    3. Startprogress ();
    4. }

Workercompleted event processing function (triggered after processing in the background)

    1. VoidBgw_runworkercompleted (ObjectSender, runworkercompletedeventargs E)
    2. {
    3. MessageBox. Show ("Processed");
    4. }

Progresschanged event processing function,

  1. VoidBgw_progresschanged (ObjectSender, progresschangedeventargs E)
  2. {
  3. If(E. userstateIs Int)
  4. {
  5. Progressbar1.value = (Int) E. progresspercentage;
  6. Label2.text = E. userstate. tostring ();
  7. }
  8. Else If(E. userstateIsList <Object>)
  9. {
  10. List <Object> TMP = (list <Object>) E. userstate;
  11. Progressbar1.value = E. progresspercentage;
  12. Label2.text = TMP [0]. tostring ();
  13. This. Label1.text = TMP [1]. tostring ();
  14. This. Listbox1.items. insert (0, TMP [2]);
  15. }
  16. }

Code running in the background

    1. private void startprogress ()
    2. {
    3. // do something
    4. bgw. reportprogress (Per, paraint);
    5. }< br>

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.