
BackgroundWoker类解决软件界面卡死问题供参考.doc
7页BackgroundWoker类解决软件界面卡死问题废话不多说,现在带着大家一步步来看看我们如何用winform中的BackgroundWorker类来解决界面卡死这个常见的问题,在这里我们用了一个弹出的进度条界面来实时报告后台耗时程序运行的进程,这个方法对大家以后进行类似的软件开发或拓展是很有用的(一个是用户体验的提升,还有就是对我们对界面的操作无影响)第一步:利用winform创建一个工程,创建的画面如下图所示:其中,Form1窗体设计如下图所示,一共有三个控件:启动按钮(线程的启动),停止按钮(线程的停止),rickTextbox控件显示打印1到999的数字(主要是模拟耗时,这边的耗时大家可以根据具体的开发来判断)ProgressForm进度条窗体如下图所示:该窗体有一个进度条progressBar1,这里我们默认设置(大家可以根据自己的需要来进行相关设置)那么对于第一步的画面设计到此结束,下面我们再看一下代码的编写,很简单的~~第二步:具体代码编写Form1中代码如下: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 WindowsFormsApplication1{ public partial class Form1 : Form { private BackgroundWorker bw=null; private ProgressForm pf; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { }//开始按钮执行事件 private void button1_Click(object sender, EventArgs e) { bw = new BackgroundWorker();//创建一个后台线程 bw.WorkerSupportsCancellation = true; //允许线程停止运行 bw.WorkerReportsProgress = true; //允许报告线程进程//线程进度事件 bw.ProgressChanged+=new ProgressChangedEventHandler(bw_ProgressChanged); //线程执行完或停止的事件 bw.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); //线程执行事件(这里就是进行耗时执行的地方,后面大家根据实际的开发可将耗时的代码放在这里面) bw.DoWork += new DoWorkEventHandler(bw_DoWork); //线程开始异步执行 bw.RunWorkerAsync(); pf = new ProgressForm(); //实例化进度条窗体对象 pf.ShowDialog();//打开进度条窗体 } void bw_DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i < 1000; i++) { //获取当前线程是否得到停止命令 if (bw.CancellationPending) { e.Cancel = true; return; } this.Invoke((MethodInvoker)delegate { this.richTextBox1.Text += i + Environment.NewLine; bw.ReportProgress(i / 10);//报告进度(这里之所以用i/100,是因为我们进度条默认最大值为100,大家根据需要更改) }); } } private void richTextBox1_TextChanged(object sender, EventArgs e) { RichTextBox textbox = (RichTextBox)sender; textbox.SelectionStart = textbox.Text.Length; textbox.ScrollToCaret(); } private void button2_Click(object sender, EventArgs e) { //停止线程 bw.CancelAsync(); } void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) {//这里是对进度条的属性进行赋值,这里我们应用了set函数,具体看进度条窗体中代码的写法,大家以后可以这么来用哦~~} pf.ProcessValue = e.ProgressPercentage; pf.ProcessStyle = ProgressBarStyle.Continuous; } void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { this.richTextBox1.Text += “线程已经停止运行”; } { pf.Close();//关闭进度条窗口 this.richTextBox1.Text = “线程已经完成”; } }}ProgressForm中代码如下: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 WindowsFormsApplication1{ public partial class ProgressForm : Form { public ProgressForm() { InitializeComponent(); } private void ProgressForm_Load(object sender, EventArgs e) { } ///
[文档可能无法思考全面,请浏览后下载,另外祝您生活愉快,工作顺利,万事如意!] / 。












