我希望点击一个按钮执行一个后台任务,同时希望,该任务未结束前,按钮事件不要重入。
//按钮事件
private void button1_Click(object sender, EventArgs e)
{
this.backgroundWorker.RunWorkerAsync();
while (this.backgroundWorker.IsBusy)
{
System.Diagnostics.Debug.WriteLine("this.backgroundWorker.IsBusy");
System.Threading.Thread.Sleep(1000);
}
}
//后台任务,仅0.1秒执行完毕
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(100);
System.Diagnostics.Debug.WriteLine("backgroundWorker_DoWork complete");
}
程序运行后,输出窗口显示:backgroundWorker_DoWork complete
但一直输出:this.backgroundWorker.IsBusy,程序进入死锁状态。
建议:
1)在触发后台时间之后,按钮应该设置为Enabled=False.
2)触发事件,同时设置WorkSupportsCancellation=True(界面设计器).
3)在DoWork事件中:
private void button1_Click(object sender, EventArgs e) { this.backgroundWorker.RunWorkerAsync(); this.Button1.Enabled = false; }
4)同时处理RunWorkerCompleted事件:
private void bgRun_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { button1.Enabled = true; }