1 using system; 2 using system. collections. generic; 3 using system. componentmodel; 4 using system. data; 5 using system. drawing; 6 using system. text; 7 using system. windows. forms; 8 using system. threading; 9 10 namespace threadupdateui 11 {12 public partial class form2: Form 13 {14 public form2 () 15 {16 initializecomponent (); 17} 18 19 private void button#click (Object sender, eventargs e) 20 {21 try 22 {23 backgroundworker1.runworkerasync (1000); 24} 25 catch (exception ES) 26 {27 28 MessageBox. show (es. message); 29} 30} 31 32 private void backgroundworker=dowork (Object sender, doworkeventargs e) 33 {34 backgroundworker BK = sender as backgroundworker; // converts serder to backgroundworker (background Operation) 35 int COUNT = (INT) (E. argument); // extract all parameters required for this operation from the argument attribute of the doworkeventargs parameter. and save it. 36 E. res Ult = longtime (count, BK, e); // assign the calculated result to the result attribute of doworkeventargs. 37} 38 random RD = new random (); 39 Long longtime (int pp, backgroundworker BK, doworkeventargs e) 40 {41 long time = 0; 42 int I = 0; 43 while (I <pp) 44 {45 I ++; 46 // determine whether to cancel the background operation 47 If (BK. cancellationpending) 48 {49 E. cancel = true; 50 break; 51} 52 else 53 {54 time + = I; 55} 56 // completion rate 57 int view = (INT) (float) i/PP * 100); 58 BK. reportprogress (View); // percentage of completed background operations, range: 0%-100% 59 system. threading. thread. sleep (5); // The faster the number is in sleep () 60} 61 return time; 62} 63 64 private void backgroundworkerappsrunworkercompleted (Object sender, runworkercompletedeventargs E) 65 {66 If (E. cancelled) 67 {68 MessageBox. show ("cancel"); 69} 70 else 71 {72 MessageBox. show (E. result. tostring (); 73} 74} 75 76 private void backgroundworkerprogress progresschanged (Object sender, progresschangedeventargs e) 77 {78 progressbar1.value = E. progresspercentage; // gets the progress percentage of an asynchronous task 79 label1.text = E. progresspercentage. tostring (); // displayed 80} 81 82 private void button2_click (Object sender, eventargs e) 83 {84 backgroundworker1.cancelasync (); 85} 86 87} 88}
Code kiss _ zero @ http://bbs.bccn.net/
Record the information and proceed with the analysis.