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 = 0; i < 100; i++) { if (worker.CancellationPending)//如果用户申请取消 { for (int k = i; k >= 0; k--) { Thread.Sleep(10); worker.ReportProgress(k);//模拟一个回滚的效果 } e.Cancel = true; return; } manualReset.WaitOne();//如果ManualResetEvent的初始化为终止状态(true),那么该方法将一直工作,直到收到Reset信号。然后,直到收到Set信号,就继续工作。 //反之亦然 Thread.Sleep(500); worker.ReportProgress(i+1); } } 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 = "暂停"; } } } }
时间: 2024-11-09 02:38:28