首页 新闻 会员 周边 捐助

为什么使用了BackgroundWorker,窗体还是处于假死状态,赐教

0
悬赏园豆:10 [已关闭问题] 关闭于 2012-12-01 07:41

private void MyBackWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                this.MyBar.Value = e.ProgressPercentage;
                this.labMessage.Text = e.UserState.ToString();
                this.labMessage.Update();
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message.ToString());
            }
        }

        private void MyBackWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //线程处理完成时
            try
            {
                MessageBox.Show("完成!");
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message.ToString());
            }
        }

        private void MyBackWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //开始执行后台程序
            try
            {  
                this.work(MyBackWorker,e);
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message.ToString());
            }
        }

        private void work(BackgroundWorker bk,DoWorkEventArgs e)
        {
            int Nums = 1000000;
            for (int i = 1; i < Nums; i++)
            {
                if (bk.CancellationPending)
                {
                    bk.ReportProgress(i, String.Format("当前值是 {0},操作被用户申请中断", i));
                    e.Cancel = true;
                    break;
                }
                bk.ReportProgress(i, String.Format("当前值是 {0} ", i));
            }
         }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                this.MyBackWorker.RunWorkerAsync();
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message.ToString());
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                this.MyBackWorker.CancelAsync();
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message.ToString());
            }
        }

勇哥哥的主页 勇哥哥 | 菜鸟二级 | 园豆:206
提问于:2012-11-30 11:39
< >
分享
所有回答(3)
0
Rich.T | 园豆:3440 (老鸟四级) | 2012-11-30 14:52
0

原因是   private void work(BackgroundWorker bk,DoWorkEventArgs e)方法将循环次数设置到1000000,而MyBar得最大值只能是100,你把循环次数设置为100,或者 bk.ReportProgress(i*100/循环次数, String.Format("当前值是 {0} ", i));

RyanCheng | 园豆:474 (菜鸟二级) | 2012-11-30 17:30

不好意思,上面分析的原因不是导致UI假死的原因,我想真正的原因是BackgroundWorker不是这么用的,你在后台线程里的foreach操作一直处于后台线程和ui线程的切换,如果你在foreach里加入线程休眠或者其他的耗时操作肯定没问题

支持(0) 反对(0) RyanCheng | 园豆:474 (菜鸟二级) | 2012-11-30 19:44
0

假死原因是因为循环速度太过快!!

勇哥哥 | 园豆:206 (菜鸟二级) | 2012-12-01 07:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册