关于使用BackgroundWorker多条线程如何控制暂完成和暂停
下面的代码,界面开启运行后,点启动后,完成后能正确输出操作完成,点击启动后立即暂停也是能正确输出操作暂停。
问题在于点启动后,再点暂停,再点启动,等完成后不会输出操作完成。
点启动后,再点暂停,再点启动,再点暂停也是不能输出操作暂停。
请问下面代码问题出在哪里,怎么修改才能正确输出。
List<BackgroundWorker> bw = new List<BackgroundWorker>();
int t = 10;
int c = 1;
public Form2()
{
InitializeComponent();
for (int i = 0; i < t; i++)
{
bw.Add(new BackgroundWorker());
bw[i].WorkerSupportsCancellation = true;
bw[i].DoWork += new DoWorkEventHandler(bw_DoWork);
bw[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (c++ == t)
{
if (e.Cancelled)
{
this.richTextBox1.Text += "操作暂停!"; ;
}
else
{
this.richTextBox1.Text += "操作完成!";
}
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
int j = Convert.ToInt32(e.Argument);
for (int i = j; i < 100; i = i + t)
{
if (((BackgroundWorker)sender).CancellationPending)
{
e.Cancel = true;
return;
}
string s1 = DateTime.Now.ToString("hh:mm:ss");
string s2 = (j+1).ToString();
this.Invoke((MethodInvoker)delegate
{
this.richTextBox1.Text += String.Format("时间:{0}-线程:{1}-数据:{2}", s1, s2, i) + Environment.NewLine;
});
System.Threading.Thread.Sleep(200);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.button1.Enabled = false;
this.button2.Enabled = true;
this.richTextBox1.Text = String.Empty;
this.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
this.button1.Enabled = true;
this.button2.Enabled = false;
this.CancelAsync();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
RichTextBox textbox = (RichTextBox)sender;
textbox.SelectionStart = textbox.Text.Length;
textbox.SelectionLength = 0;
textbox.ScrollToCaret();
}
private void RunWorkerAsync()
{
for (int i = 0; i < t; i++)
{
bw[i].RunWorkerAsync(i);
}
}
private void CancelAsync()
{
for (int i = 0; i < t; i++)
{
bw[i].CancelAsync();
}
}