在桌面程序开发中,如果需要执行操作数据库或访问网络等耗时操作,会导致UI线程堵塞、界面卡死,所以应当把耗时操作放到新建线程中执行,但其他线程不能修改UI,这导致操作进度无法回馈给用户界面。
解决方法有很多,其中BackgroundWorker是.NET里用来执行多线程任务的控件,它允许编程者在一个单独的线程上执行一些操作。
代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Linq; 5 using System.Text; 6 using System.Threading; 7 using System.Windows; 8 using System.Windows.Controls; 9 using System.Windows.Data; 10 using System.Windows.Documents; 11 using System.Windows.Input; 12 using System.Windows.Media; 13 using System.Windows.Media.Imaging; 14 using System.Windows.Navigation; 15 using System.Windows.Shapes; 16 17 namespace BGW 18 { 19 /// <summary> 20 /// MainWindow.xaml 的交互逻辑 21 /// </summary> 22 public partial class MainWindow : Window 23 { 24 BackgroundWorker bgWorker = new BackgroundWorker(); 25 public MainWindow() 26 { 27 InitializeComponent(); 28 backgroundWorkerInit(); 29 } 30 31 private void backgroundWorkerInit() 32 { 33 //使BackgroundWorker能够报告工作进度 34 bgWorker.WorkerReportsProgress = true; 35 //使BackgroundWorker支持异步取消 36 bgWorker.WorkerSupportsCancellation = true; 37 //绑定事件,在BackgroundWorker.RunWorkerAsync()时发生 38 bgWorker.DoWork += Work; 39 //绑定事件,在BackgroundWorker.ReportProgress(int)时发生 40 bgWorker.ProgressChanged += ProgressChanged; 41 //绑定事件,在BackgroundWorker完成或被终止时发生 42 bgWorker.RunWorkerCompleted += RunWorkerCompleted; 43 } 44 45 private void btn_start_Click(object sender, RoutedEventArgs e) 46 { 47 if (!bgWorker.IsBusy) 48 { 49 pb.Value = 0; 50 pb.Maximum = 100; 51 tb.Clear(); 52 //开始后台异步操作 53 bgWorker.RunWorkerAsync(); 54 } 55 } 56 57 private void btn_abort_Click(object sender, RoutedEventArgs e) 58 { 59 //取消后台异步操作 60 bgWorker.CancelAsync(); 61 } 62 63 #region BackgroundWorker事件 64 65 private void Work(object sender, DoWorkEventArgs args) 66 { 67 BackgroundWorker worker = sender as BackgroundWorker; 68 for (int i = 1; i <= 100; i++) 69 { 70 if (worker.CancellationPending) 71 { 72 args.Cancel = true; 73 break; 74 } 75 else 76 { 77 //报告进度 78 worker.ReportProgress(i); 79 //模拟费时操作 80 Thread.Sleep(100); 81 } 82 } 83 } 84 85 private void ProgressChanged(object sender, ProgressChangedEventArgs args) 86 { 87 pb.Value = args.ProgressPercentage; 88 tb.Text = String.Format("第{0}项工作\n", args.ProgressPercentage) + tb.Text; 89 } 90 91 private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs args) 92 { 93 if (args.Cancelled) 94 { 95 MessageBox.Show("手动取消", "Message"); 96 } 97 else 98 { 99 MessageBox.Show("正常结束", "Message"); 100 } 101 } 102 103 #endregion 104 } 105 }
运行截图:
时间: 2024-10-22 08:16:20