C# BackgroundWorker的Bug???
废话不多说,上代码:
public partial class Form1 : Form { BackgroundWorker _bgWorker; int count; public Form1() { InitializeComponent(); _bgWorker = new BackgroundWorker(); _bgWorker.WorkerReportsProgress = true; _bgWorker.WorkerSupportsCancellation = true; _bgWorker.DoWork += _bgWorker_DoWork; ; _bgWorker.ProgressChanged += _bgWorker_ProgressChanged; ; _bgWorker.RunWorkerCompleted += _bgWorker_RunWorkerCompleted; timer1.Enabled = true; } private void toolStripButtonStart_Click(object sender, EventArgs e) { count = 0; _bgWorker.RunWorkerAsync(); } private void toolStripButtonStop_Click(object sender, EventArgs e) { _bgWorker.CancelAsync(); // 加上这三行代码就会导致不能触发_bgWorker_RunWorkerCompleted,_bgWorker.IsBusy一直未true阻塞在这个地方 while (_bgWorker.IsBusy) { Thread.Sleep(100); } } private void _bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { System.Windows.Forms.MessageBox.Show("Test Done"); } private void _bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { toolStripLabelIsRunning.Text = count++.ToString(); } private void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bgWorker = sender as BackgroundWorker; bool boolFlag=false; while (!bgWorker.CancellationPending) { Thread.Sleep(100); boolFlag = !boolFlag; if (boolFlag) { bgWorker.ReportProgress(1); } }
Debug.WriteLine("Successfully Exite");
}
}
在一个简单的form中添加一个BackgroundWorker,并注册DoWork,ProgressChanged,RunWorkerCompleted事件
在如图中toolStripButtonStop_Click 界面响应事件函数中如果没有加以下三行代码一切运行正常,Start后正常运行,Stop后正常的推出并触发RunWorkerCompleted事件,
while (_bgWorker.IsBusy)
{
Thread.Sleep(100);
}
但是如果toolStripButtonStop_Click 界面响应事件函数中加入了这三行代码则RunWorkerCompleted事件永远都不会被触发,_bgWorker.IsBusy永远都是true导致toolStripButtonStop_Click 界面响应事件函数无法退出(实际上_bgWorker_DoWork函数早就已经退出了,在输出窗口中可以看到_bgWorker_DoWork函数退出前运行了 Debug.WriteLine("Successfully Exite"); 输出的Successfully Exite字符串)