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事件spa

在如圖中toolStripButtonStop_Click 界面響應事件函數中若是沒有加如下三行代碼一切運行正常,Start後正常運行,Stop後正常的推出並觸發RunWorkerCompleted事件,code

           while (_bgWorker.IsBusy) orm

           { blog

               Thread.Sleep(100);事件

            }ip

可是若是toolStripButtonStop_Click 界面響應事件函數中加入了這三行代碼則RunWorkerCompleted事件永遠都不會被觸發,_bgWorker.IsBusy永遠都是true致使toolStripButtonStop_Click 界面響應事件函數沒法退出(實際上_bgWorker_DoWork函數早就已經退出了,在輸出窗口中能夠看到_bgWorker_DoWork函數退出前運行了 Debug.WriteLine("Successfully Exite"); 輸出的Successfully Exite字符串字符串


請教各位大神,這是爲何???

相關文章
相關標籤/搜索