Note: In this example, we will learn more about the workerreportsprogress, workersuppscanscancdllation attributes, and dowork, proesschanged, and runworkercompleted events of backgroundworker.
1 Public Partial Class Form1: Form 2 { 3 Public Form1 () 4 { 5 Initializecomponent (); 6 7 // Gets or sets a value that indicates whether the BW report can report progress updates. 8 Backgroundworker1.workerreportsprogress = True ; 9 // Gets or sets a value that indicates whether BW supports asynchronous cancellation. 10 Backgroundworker1.workersuppscanscancellation =True ; 11 Buttonstop. Enabled = False ; 12 } 13 14 Private Void Buttonstart_click ( Object Sender, eventargs E) 15 { 16 Richtextbox1.text = " Starting to generate a random number of less than 10000 ...... \ N " ; 17 Buttonstart. Enabled = False ; 18 Buttonstop. Enabled = True ; 19 // Start operations in the background 20 Backgroundworker1.runworkerasync (); 21 } 22 23 Private Void Backgroundworkerincludowork ( Object Sender, doworkeventargs E) 24 { 25 // Do not directly use the component Instance name (backgroundworker1) because there are many 26 // Backgroundworker 27 // Use it through the following Conversions 28 Backgroundworker worker = sender As Backgroundworker; 29 // The following content is equivalent to the content to be processed by the thread. Note: do not deal with controls in this event 30 Random r = New Random (); 31 Int Numcount = 0 ; 32 While (Worker. cancellationpending = False ) 33 { 34 Int Num = R. Next ( 10000 ); 35 If (Num % 5 = 0 ) 36 { 37 Numcount ++ ; 38 // Raise BW. progresschanged () event 39 Worker. reportprogress ( 0 , Num ); 40 Thread. Sleep ( 1000 ); 41 } 42 } 43 // Doworkeventargs. Result gets or sets the value indicating the asynchronous operation result. 44 E. Result = Numcount; 45 } 46 47 48 Private Void Backgroundworker1_progresschanged ( Object Sender, progresschangedeventargs E) 49 { 50 // Object progresschangedeventargs. userstate to obtain the unique user status 51 Int Num = ( Int ) E. userstate; 52 Richtextbox1.text + = num + " , " ; 53 } 54 55 Private Void Backgroundworkerappsrunworkercompleted ( Object Sender, runworkercompletedeventargs E) 56 { 57 If (E. Error = Null ) 58 { 59 Richtextbox1.text + = " \ N operation stopped, a total " + E. Result + " Random number divisible by 5 " ; 60 } 61 Else 62 { 63 Richtextbox1.text + = " \ N errors occurred during operation: " + E. error; 64 } 65 66 } 67 68 Private Void Buttonstop_click (Object Sender, eventargs E) 69 { 70 // Request to cancel the pending operation 71 Backgroundworker1.cancelasync (); 72 Buttonstop. Enabled = False ; 73 Buttonstart. Enabled = True ; 74 } 75 }