在WinForm中经常遇到一些费时的操作界面,比如统计某个磁盘分区的文件夹或者文件数目,如果分区很大或者文件过多的话,处理不好就会造成“假死”的情况,或者报“线程间操作无效”的异常,为了解决这个问题,可以使用委托来处理,在.net2.0中还可以用BackgroundWorker类。
BackgroundWorker类是.net 2.0里新增加的一个类,对于需要长时间操作而不需要用户长时间等待的情况可以使用这个类。
注意确保在 DoWork 事件处理程序中不操作任何用户界面对象。而应该通过 ProgressChanged 和 RunWorkerCompleted 事件与用户界面进行通信。
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
-
- namespace WinFormReport
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public partial class MainForm : Form
- {
- private BackgroundWorker worker = new BackgroundWorker();
- public MainForm()
- {
- InitializeComponent();
- worker.WorkerReportsProgress = true;
- worker.WorkerSupportsCancellation = true;
-
- worker.DoWork += new DoWorkEventHandler(DoWork);
-
- worker.ProgressChanged += new ProgressChangedEventHandler(ProgessChanged);
-
- worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteWork);
- }
-
-
- public void DoWork(object sender, DoWorkEventArgs e)
- {
- e.Result = ComputeFibonacci(worker, e);
- }
-
- public void ProgessChanged(object sender, ProgressChangedEventArgs e)
- {
- this.progressBar1.Value = e.ProgressPercentage;
- }
-
- public void CompleteWork(object sender, RunWorkerCompletedEventArgs e)
- {
- MessageBox.Show("完成!");
- }
-
- private int ComputeFibonacci(object sender, DoWorkEventArgs e)
- {
- for (int i = 0; i < 1000; i++)
- {
- if (worker.CancellationPending)
- {
- e.Cancel = true;
- return -1;
- }
- else
- {
- int percent = 100 * i / 1000;
- worker.ReportProgress(percent);
- }
- System.Threading.Thread.Sleep(10);
- }
- return -1;
- }
-
- private void btnStart_Click(object sender, EventArgs e)
- {
- worker.RunWorkerAsync();
- btnStart.Enabled = false;
- btnPause.Enabled = true;
- }
-
- private void btnPause_Click(object sender, EventArgs e)
- {
- btnPause.Enabled = false;
- btnStart.Enabled = true;
- worker.CancelAsync();
- }
-
- }
- }
在此感谢luols指出其中的一个小bug。
本文转自周金桥51CTO博客,原文链接: http://blog.51cto.com/zhoufoxcn/166053,如需转载请自行联系原作者