1. 从工具栏拖一个BackgroundWorker控件,设置其属性WorkerReportsProgress为true 2. 要让worker开始工作,执行如下代码: mBackgroundWorker.RunWorkerAsync(arg); 这里有重写,如果不需要传递参数直接mBackgroundWorker.RunWorkerAsync(); 3. 编辑DoWork事件代码: e.Argument为mBackgroundWorker.RunWorkerAsync(arg);对应的参数 之所以使用进度条,肯定是有循环的,在循环中报告进度: worker.ReportProgress(i * 100 / totalNum, obj ); 其中{dy}个参数是当前进度的百分之多少,obj为你要传递的UserState,如果没有可以不要 4. 编辑ProgressChanged事件代码: e.ProgressPercentage为进度的百分数,e.UserState为刚才传递过来的object 在这个事件中可以调用ui的进度条和其他控件: mToolStripProgressBar.Value = e.ProgressPercentage; 5. 编辑RunWorkerCompleted事件代码: 工作完成了告诉ui 示例代码:一个简单的刷网页流量的小工具 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; using System.Net; using System.Threading; namespace shua { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { backgroundWorker1.RunWorkerAsync(textBox1.Text); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = (BackgroundWorker)sender; string url = e.Argument.ToString(); int num = int.Parse(textBox2.Text); for (int i = 0; i < num; i++) { if (!worker.CancellationPending) { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); response.Close(); Thread.Sleep(100); worker.ReportProgress(i * 100 / num, i); } } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; label3.Text = e.UserState.ToString(); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show("ok"); } } } |