1. The sample program is a console application that implements parallel execution of the main thread and the background thread to achieve an array assignment effect.
You can stop a background thread halfway.
2. The results of the implementation image are as follows:
Normal execution Ends:
To stop a background thread halfway:
3. Code
Using system;using system.collections.generic;using system.linq;using system.text;using System.ComponentModel;using System.threading;namespace BackgroundWorker Multithreading {class Dobackgroundwork {BackgroundWorker Bgworker = new back Groundworker (); Public int[] Backarray{get;private set;} public bool Completednormally {get; private set;} Construction method Public Dobackgroundwork (int[] array) {This.backarray = array; Bgworker.workerreportsprogress = true; Bgworker.workersupportscancellation = true; Bgworker.dowork + = Dowork_handler; Bgworker.progresschanged + = Progresschanged_handler; bgworker.runworkercompleted + = Runworkercompleted_handler; } public void Startworker () {if (!bgworker.isbusy) {Bgworker.runworke Rasync (); }} public static int[] Calculatethesequence (int[] array) { for (int i = 0; i < array. Length; i++) {Array[i] = ten * I; } return array; } public void Dowork_handler (object sender, DoWorkEventArgs args) {BackgroundWorker worker = Sen Der as BackgroundWorker; Perform a background calculation for (int i = 0; i < i++) {//each iteration checks if the IF (worker . cancellationpending) {args. Cancel = true; Worker. ReportProgress (-1); Break } else {//If not canceled, continue to calculate calculatethesequence (Backarray ); Worker. ReportProgress ((i+1) *10); Let the program slow down so that it can be beautifully output a little thread.sleep (100); }}}//Handle the input of the background thread private void Progresschanged_handler (object Sender,progresschangedeventa RGS args) { string output = args. Progresspercentage = =-1? "Cancelled": String. Format ("Back: {0}%", args.) Progresspercentage); Console.WriteLine (output); }//After the background thread completes, summarize and save the sum private void Runworkercompleted_handler (object Sender,runworkercompletedeventargs args) {completednormally =!args. Cancelled; } public void Cancel () {if (bgworker.isbusy) {bgworker.cancelasync (); }}} class program {static void Main () {Giveinstructionstot Heuser (); Outputthesummaryheaders (); Create and start a background thread int[] backarray=new int[10]; Dobackgroundwork BGW = new Dobackgroundwork (Backarray); Bgw. Startworker (); The main thread starts the calculation, for each cycle, checks whether the user has canceled the background thread//After the calculation, a short hibernation, so that the program can be slower, so that the main thread will not be faster than the background threads int[] Mainarray = new int[1 0]; for (inti = 0; I < 10; i++) {if (Program.checkforcancelinput ()) BGW. Cancel (); Calculatethesequencemain (Mainarray); Thread.Sleep (100); Console.WriteLine ("Main: {0}%", (i + 1) * 10); } summarizeresults (BGW, Mainarray); Console.ReadLine (); public static void Giveinstructionstotheuser () {Console.WriteLine ("This program computes the values of two arrays in parallel between the main thread and the background thread.) \ n "); Console.WriteLine ("First press <Enter> key to start execution of main thread main and background thread back."); Console.WriteLine ("Second press <Enter> to stop executing background thread back."); Console.ReadLine (); } public static void Outputthesummaryheaders () {Console.WriteLine ("------------------------"); } private static void Summarizeresults (Dobackgroundwork BGW, int[] mainarray) {Console.wri Teline ("\ n" Run Result: "); Console.WriteLine ("Main completed!"); for (int i = 0; i < mainarray.length;i++) {Console.WriteLine ("mainarray[" + i + "]: "+ mainarray[i]); } if (BGW. completednormally) {Console.WriteLine ("\nbackground completed!"); for (int i = 0; i < bgw.backArray.Length; i++) {Console.WriteLine ("backarray[" + i + "]:" + bgw.backarray[i]); }} else {Console.WriteLine ("\nbackground Cancelled. "); }} public static bool Checkforcancelinput () {bool Docancel = Console.keyavai lable; if (docancel) Console.readkey (); return docancel; } public static int[] Calculatethesequencemain (int[] array) {for (int i = 0; i < array. Length; i++) {Array[i] = i * i; }return array; } }}
C # Multithreading BackgroundWorker class using small cases