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());
}
}
原因是 private void work(BackgroundWorker bk,DoWorkEventArgs e)方法将循环次数设置到1000000,而MyBar得最大值只能是100,你把循环次数设置为100,或者 bk.ReportProgress(i*100/循环次数, String.Format("当前值是 {0} ", i));
不好意思,上面分析的原因不是导致UI假死的原因,我想真正的原因是BackgroundWorker不是这么用的,你在后台线程里的foreach操作一直处于后台线程和ui线程的切换,如果你在foreach里加入线程休眠或者其他的耗时操作肯定没问题
假死原因是因为循环速度太过快!!