1. The program implements a simple WPF program that uses the BackgroundWorker class to assign a value to a progress bar in a background thread.
The results of the operation are as follows:
The background thread ends up running correctly:
The background thread was canceled halfway:
2. The program only modifies the MainWindow.xaml and MainWindow.xaml.cs files, and the contents of two files are as follows
MainWindow.xaml file:
<window x:class= "Simpleworker.mainwindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation " xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml " title=" MainWindow "height=" 150 " Width= "$" > <StackPanel> <progressbar name= "ProgressBar" height= "width=" "10" margin= " ></ProgressBar> <button name= "btnprocess" width= "" click= "Btnprocess_click" margin= "5" > Start background task </Button> <button name= "Btncancel" width= "click=" Btncancel_click "5" > Cancel background Tasks < /button> </StackPanel></Window>
AinWindow.xaml.cs file:
Using system.windows;using system.componentmodel;using system.threading;namespace simpleworker{//<summary> Interactive logic for MainWindow.xaml///</summary> public partial class Mainwindow:window {BackgroundWorker Bgworker = new BackgroundWorker (); Public MainWindow () {InitializeComponent (); Bgworker.workerreportsprogress = true; Bgworker.workersupportscancellation = true; Bgworker.dowork + = Dowork_handler; Bgworker.progresschanged + = Progresschanged_handler; bgworker.runworkercompleted + = Runworkercompleted_handler; private void Btnprocess_click (Object Sender,routedeventargs e) {if (!bgworker.isbusy) {Bgworker.runworkerasync (); }} private void Progresschanged_handler (object sender, ProgressChangedEventArgs args) {p Rogressbar.value = args. Progresspercentage; } private void Dowork_handler (object Sender,doworkeventargs args) {BackgroundWorker worker = sender A s BackgroundWorker; for (int i = 1; i <=; i++) {if (worker. cancellationpending) {args. Cancel = true; Break } else {worker. ReportProgress (I*10); Thread.Sleep (500); }}} private void Runworkercompleted_handler (object Sender,runworkercompletedeventargs args) {progressbar.value = 0; if (args. Cancelled) {MessageBox.Show ("Background task has been canceled. "," message "); } else {MessageBox.Show ("background task ends normally. "," message "); }} private void Btncancel_click (Object Sender,routedeventargs e) {Bgworker.cancelasync () ; } }}
C # multithreaded BackgroundWorker class using small case-WPF program