XAML代码:
<Window x:Class="backgroundtest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="160" Width="237"> <StackPanel Height="100" Width="196"> <ProgressBar Name="progressBar" Height="20" Width="200" Margin="10" /> <Button Name="btnProcess" Width="100" Click="btnProcess_click" Margin="5">process</Button> <Button Name="btncancel" Width="100" Click="btnCancel_Click" Margin="5">cancel</Button> </StackPanel> </Window>
后台代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace backgroundtest { /// <summary> /// Interaction 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_Handle; bgWorker.ProgressChanged += ProgressChanged_Handle; bgWorker.RunWorkerCompleted += RunWorkerCompleted_Handler; } private void btnProcess_click(object sender, RoutedEventArgs e) { if (!bgWorker.IsBusy) { bgWorker.RunWorkerAsync(); } } private void ProgressChanged_Handle(Object sender,ProgressChangedEventArgs args) { progressBar.Value = args.ProgressPercentage; } private void DoWork_Handle(object sender, DoWorkEventArgs args) { BackgroundWorker worker = sender as BackgroundWorker; for (int i = 0; i < 10; 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("process was cancelled.", "process cancelled"); } else { MessageBox.Show("process completed normally.", "process completed"); } } private void btnCancel_Click(object sender, RoutedEventArgs e) { bgWorker.CancelAsync(); } } }