Backgroundworker can be used to start background threads.
Main events and parameters:
1. dowork -- this event is triggered when the backgroundworker. runworkerasync method is executed and the doworkeventargs parameter is passed;
2. runworkercompleted: this event is triggered when asynchronous operations are completed or terminated midway through.
To terminate the background operation in advance, you can call the backgroundworker. cancelasync method.
Detects backgroundworker in the function that handles dowork events. whether the cancellationpending attribute is true. If it is true, it indicates that the asynchronous call has been canceled and doworkeventargs. the cancel attribute is set to true (the second parameter passed to the function for processing dowork events), so that when the asynchronous call is exited, you can let the function that handles the runworkercompleted event know whether to exit normally or midway through.
3. progresschanged -- Changes in the processing status obtained during Operation Processing, through backgroundworker. the reportprogress (INT) method triggers this event and passes progresschangedeventargs, which includes the percentage of processing. This parameter is used to set the progressbar control on the UI interface.
Main Methods:
1. backgroundworker. runworkerasync -- the method of "starting" Asynchronous call has two reloads: runworkerasync () and runworkerasync (Object argument). The second overload provides a parameter for asynchronous call. (If multiple parameters need to be passed, use a class to pass them ). After this method is called, The dowork event is triggered, and the doworkeventarg parameter is passed to the function for processing the dowork event, which contains the parameters passed by runworkerasync. You can perform complex operations in the corresponding dowork processing functions.
2. backgroundworker. reportprogress -- You need to constantly report the progress to the user in a lengthy operation. In this way, you can call reportprogress (INT percent) to trigger the progresschanged event when you call the reportprogress method. Provides an integer between 0 and 100, which indicates the percentage of background activities completed. You can also provide any object as the second parameter, allowing you to pass status information to the event handler. As the progresschangedeventargs parameter attribute passed to this process, the percentage and your own object (if provided) will be passed to the progresschanged event handler. These attributes are named progresspercentage and userstate respectively, and your event handler can use them in any way you need. (Note: This method is only available when the backgroundworker. workerreportsprogress attribute is set to true ).
3. backgroundworker. cancelasync -- this method is called when you need to exit the asynchronous call. However, this is not enough because it only sets the backgroudworker. cancellationpending attribute to true. You need to constantly check whether backgroudworker. cancellationpending is true during asynchronous call processing. If it is true, exit. (Note: This method is only available when the backgroundworker. workersuppscanscancellation attribute is set to true ).
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 whether the application has requested to cancel background operations. 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) to the doworkeventargs of the dowork event. argument, because only one parameter can be passed here, in actual application, encapsulate a class, and pass the entire instantiated class as the object of runworkerasync 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 transfer 3: Before the dowork event ends, the result data generated by the background thread is assigned to doworkeventargs. result, while calling the runworkercompleted event runworkercompletedeventargs. Result attribute in the runworkercompleted event to obtain 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 there are too many files, if the processing is not good, it may cause a "false" situation or an exception that "Inter-thread operation is invalid". To solve this problem, you can use a delegate to handle it. the backgroundworker class can also be used in net2.0.
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.
View code
Public partial class mainwindow: window {private backgroundworker m_backgroundworker; // declare the background object public mainwindow () {initializecomponent (); m_backgroundworker = new backgroundworker (); // instantiate the backend object expiration = true; // you can set m_backgroundworker.workersuppscanscancellation to true; // you can disable m_backgroundworker.dowork + = new doworkeventhandler (dowork); m_backgroundworke R. progresschanged + = new progresschangedeventhandler (updateprogress); Updated + = new runworkercompletedeventhandler (completedwork); executed (this);} void dowork (Object sender, doworkeventargs E) {backgroundworker BW = sender as backgroundworker; mainwindow win = E. argument As mainwindow; int I = 0; while (I <= 100) {If (BW. cancellationpen Ding) {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 button#click (Object sender, routedeventargs e) {m_backgroundworker.cancelasync ();}}