private void btnStart_Click(object sender, EventArgs e) { WorkRange wr = new WorkRange { nStart = 100, nEnd = 1000000 }; bgWork.RunWorkerAsync(wr); //开始执行后台操作 }
public event CompleteHandler Complete; //提供一定模板下的方法供具体实现 public ClsBgWorker(WorkRange wr) { Range = wr; BgWorker = new BackgroundWorker(); BgWorker.WorkerSupportsCancellation = true; BgWorker.DoWork += new DoWorkEventHandler(DoWork); BgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted); }
private void btnStart_Click(object sender, EventArgs e) { WorkRange wr = new WorkRange(); id += 1; wr.id = id; wr.nStart = new Random().Next(1, 1000) * 100; wr.nEnd = new Random().Next(1, 1000) * 1000; bgWork = new ClsBgWorker(wr); bgWork.Complete += new ClsBgWorker.CompleteHandler(DoComplete); lstRange.Items.Add(wr.id.ToString() + '\t' + wr.nStart.ToString() + '\t' + wr.nEnd.ToString()); bgWork.Run(); }
private void btnStart_Click(object sender, EventArgs e) { WorkRange wr = new WorkRange(); id = id == 0 ? 1 : 0; wr.id = id; wr.nStart = new Random().Next(1, 1000) * 100; wr.nEnd = new Random().Next(1, 1000) * 1000; bgWork = new ClsBgWorker(wr, this); bgWork.Complete += new ClsBgWorker.CompleteHandler(DoComplete); bgWork.SendMessage += new ClsBgWorker.MessageHandler(SendMessage); lstRange.Items.Clear(); lstResult.Items.Clear(); bgWork.Run(); }
private void bgWork_DoWork(object sender, DoWorkEventArgs e) { WorkRange wr = (WorkRange)e.Argument; int sum = 0; for (int k = 0; k < 1000; k++) { if (bgWork.CancellationPending) //指示应用程序是否已请求取消后台操作 { e.Cancel = true; return; } for (int i = wr.nStart; i < wr.nEnd; i++) { sum += i; } } e.Result = sum; }
private void btnStart_Click(object sender, EventArgs e) { bgWork = new BackgroundWorker(); bgWork.DoWork += new DoWorkEventHandler(DoWork); bgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted); WorkRange wr = new WorkRange(); if ((Button)sender == btnStart1) { wr.id = 1; wr.nStart = 100; wr.nEnd = 100000; } else if ((Button)sender == btnStart2) { wr.id = 2; wr.nStart = 500; wr.nEnd = 200000; } bgWork.RunWorkerAsync(wr); //开始执行后台操作 }