我有一个表单,会启动一个BackgroundWorker,该worker应该更新表单自己的文本框(在主线程上),因此需要调用Invoke((Action) (...));
。
如果我在HandleClosingEvent
中只是执行bgWorker.CancelAsync()
,那么当我调用Invoke(...)
时会出现ObjectDisposedException
异常,这很容易理解。但如果我等待bgWorker完成,那么.Invoke(...)将永远不会返回,这也很容易理解。
有什么办法可以关闭这个应用程序而不出现异常或死锁吗?
以下是Form1类的3个相关方法:
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
}