如何阻止后台工作人员在表单的闭幕式上工作?我有一个生成背景工作器的表单,它应该更新表单自己的文本框(在主线程上),因此Invoke((Action) (...));打电话。如果在HandleClosingEvent我只是想bgWorker.CancelAsync()然后我得到ObjectDisposedException在……上面Invoke(...)打电话,可以理解。但如果我坐在HandleClosingEvent等待bgWorker的完成,而不是.invoke(.)永远不会回来,也是可以理解的。任何想法,我如何关闭这个应用程序而没有得到异常,或僵局?以下是简单Form 1类的三种相关方法: public Form1() {
InitializeComponent();
Closing += HandleClosingEvent;
this.bgWorker.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
while (!this.bgWorker.CancellationPending) {
Invoke((Action) (() => { this.textBox1.Text = Environment.TickCount.ToString(); }));
}
}
private void HandleClosingEvent(object sender, CancelEventArgs e) {
this.bgWorker.CancelAsync();
/////// while (this.bgWorker.CancellationPending) {} // deadlock
}
3 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
private bool closePending;protected override void OnFormClosing(FormClosingEventArgs e) { if (backgroundWorker1.IsBusy) { closePending = true; backgroundWorker1.CancelAsync(); e.Cancel = true; this.Enabled = false; // or this.Hide() return; } base.OnFormClosing(e);}void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (closePending) this.Close(); closePending = false; // etc...}
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
List<Thread> bgWorkersThreads = new List<Thread>();
bgWorkesThreads.Add(Thread.CurrentThread);
foreach (Thread thread in this.bgWorkersThreads) { thread.Abort(); }
CustomTaskPane
COM Exception
CancelAsync()
backgroundworkers
DocumentBeforeClose
- 3 回答
- 0 关注
- 407 浏览
添加回答
举报
0/150
提交
取消