1.程序实现了一个简单的使用了BackgroundWorker类的WPF程序,用于在后台线程给进度条赋值。
运行结果如下:
后台线程正常运行结束:
后台线程中途被取消:
2.程序仅修改了 MainWindow.xaml 文件和 MainWindow.xaml.cs 文件,两个文件内容如下
MainWindow.xaml 文件:
<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="250"> <StackPanel> <ProgressBar Name="progressBar" Height="20" Width="200" Margin="10"></ProgressBar> <Button Name="btnProcess" Width="100" Click="btnProcess_Click" Margin="5">开始后台任务</Button> <Button Name="btnCancel" Width="100" Click="btnCancel_Click" Margin="5">取消后台任务</Button> </StackPanel> </Window>
using System.Windows; using System.ComponentModel; using System.Threading; namespace SimpleWorker { /// <summary> /// 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) { progressBar.Value = args.ProgressPercentage; } private void DoWork_Handler(object sender,DoWorkEventArgs args) { BackgroundWorker worker = sender as BackgroundWorker; for (int i = 1; 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("后台任务已经被取消。", "消息"); } else { MessageBox.Show("后台任务正常结束。","消息"); } } private void btnCancel_Click(object sender,RoutedEventArgs e) { bgWorker.CancelAsync(); } } }
C#多线程 BackgroundWorker类使用小例-WPF程序
原文地址:http://blog.csdn.net/xuanwuziyou/article/details/41721373