为了避免代码的复杂化,上面代码我没有做更多的体验修改,比如点击开始的按钮,开始的按钮应该为不可用状态,点击停止按钮后停止按钮不可用状态,激活开始按钮。
下面我们将继续升级,如何来获知线程是否已经执行完成或者线程已经停止了呢
复制代码 代码如下:
BackgroundWorker bw = null;
private void button1_Click(object sender, EventArgs e)
{
bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
//线程完成或者停止发生的事件
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
bw.CancelAsync();
}
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;
});
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
this.richTextBox1.Text += "线程已经停止";
}
else
{
this.richTextBox1.Text += "线程已经完成";
}
}
到现在为止你可以自己去用BackgroundWorker创建一个线程了,你已经了解它了,当然BackgroundWorker还有一个ReportProgress滚动条事件,可以显示进度,我暂且认为它是多余的,因为大部分进度都可以通过bw_DoWork来控制实现。下面我们继续完善BackgroundWorker,加入暂停和继续功能。
再拖动一个button控件到界面,BackgroundWorker的暂停和继续我们使用ManualResetEvent。
复制代码 代码如下:
BackgroundWorker bw = null;
//创建ManualResetEvent
ManualResetEvent mr = new ManualResetEvent(true);
private void button1_Click(object sender, EventArgs e)
{
bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
bw.CancelAsync();
}
private void button3_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Text == "暂停")
{
mr.Reset();
b.Text = "继续";
}
else
{
mr.Set();
b.Text = "暂停";
}
}
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;
});
//接受指令
mr.WaitOne();
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
this.richTextBox1.Text += "线程已经停止";
}
else
{
this.richTextBox1.Text += "线程已经完成";
}
}