上面代码中的停止不是能立即停止,这个就和开车一样,开的越快,刹车的后拖行的距离越长,同理,开启的线程的越多,完全暂停需要的时间越长,不知我说的是否正确。另外我也想问一下是否能真正的全部线程停止,点停止后全部线程立即停止。
下面我们继续加入暂停和继续的功能,一样的道理,我们使用List<ManualResetEvent>。
复制代码 代码如下:
List<BackgroundWorker> bws = new List<BackgroundWorker>();
List<ManualResetEvent> mrs = new List<ManualResetEvent>();
int t = 10;
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < t; i++)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.WorkerSupportsCancellation = true;
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bws.Add(bw);
bw.RunWorkerAsync(i);
mrs.Add(new ManualResetEvent(true));
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < t; i++)
{
bws[i].CancelAsync();
}
}
private void button3_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Text == "暂停")
{
for (int i = 0; i < mrs.Count; i++)
{
mrs[i].Reset();
}
b.Text = "继续";
}
else
{
for (int i = 0; i < mrs.Count; i++)
{
mrs[i].Set();
}
b.Text = "暂停";
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
int j = Convert.ToInt32(e.Argument);
for (int i = j; i < 1000; i = i + t)
{
if (((BackgroundWorker)sender).CancellationPending)
{
e.Cancel = true;
return;
}
string item = String.Format("线程{0}正在操作数据{1}", j + 1, i);
this.Invoke((MethodInvoker)delegate
{
this.richTextBox1.Text += item + Environment.NewLine;
});
Thread.Sleep(200);
mrs[j].WaitOne();
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bws.Remove(sender as BackgroundWorker);
if (bws.Count == 0)
{
if (e.Cancelled)
{
this.richTextBox1.Text += "线程已经停止";
}
else
{
this.richTextBox1.Text += "线程已经完成";
}
}
}