这也是今天讨论的话题。取消是默认就支持的,而暂停则默认不支持。但通过ManualResetEvent可以对其进行干预。 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.Threading; namespace BackgroundWorkderPauseSample
{
public partial class MainForm : Form
{
BackgroundWorker worker = null; public MainForm()
{
InitializeComponent();
Load += new EventHandler(Form1_Load);
} void Form1_Load(object sender, EventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); } void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
} void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
MessageBox.Show("用户取消了操作");
else
{
MessageBox.Show("正常完成了操作");
} } void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = ; i < ; i++)
{
if (worker.CancellationPending)//如果用户申请取消
{
for (int k = i; k >= ; k--)
{
Thread.Sleep();
worker.ReportProgress(k);//模拟一个回滚的效果
}
e.Cancel = true;
return;
} manualReset.WaitOne();//如果ManualResetEvent的初始化为终止状态(true),那么该方法将一直工作,直到收到Reset信号。然后,直到收到Set信号,就继续工作。
//反之亦然
Thread.Sleep();
worker.ReportProgress(i+); }
} private void btStart_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
} private void btCancel_Click(object sender, EventArgs e)
{
worker.CancelAsync();
} private ManualResetEvent manualReset = new ManualResetEvent(true); private void btPause_Click(object sender, EventArgs e)
{
if (btPause.Text == "暂停")
{
manualReset.Reset();//暂停当前线程的工作,发信号给waitOne方法,阻塞
btPause.Text = "继续";
}
else
{
manualReset.Set();//继续某个线程的工作
btPause.Text = "暂停";
}
}
}
}
这个程序运行的效果大致如下
一。正常状态
image
二。暂停状态
image 三。恢复状态 image 作为演示,代码比较简单,没有对worker的一些状态进行判断以及按钮相应的设置。仅供参考