我遇到了我在这里问的问题的变体。我有一个类扩展System.Windows.Form
,而不是一个类扩展System.Windows.UserControl
,它没有FormClosing
事件。
我想过向用户控件添加一个Close
方法,在该方法中,我告诉本机线程停止。当它停止时,它会向用户控件引发一个事件,该控件对自身调用Dispose
。这种方法的问题在于,从对象调用Dispose
来处置(自杀?(似乎是一种不好的做法,我不得不编写一个什么都不做的终结器(以避免双重处置(,这感觉更糟......
建议?
更新:我的用户控件位于扩展System.Windows.Forms.ToolStripControlHost
的类中,并且该类的实例位于主应用程序窗体中。
我会向用户控件添加某种方法,并在事件FormClosing
形式中调用它......
用户控件中的方法将阻塞,以便在处置完成之前不会返回。
但是,您可以在 Closing 事件中取消关闭,禁用窗体,在后台执行某些操作,完成后,从代码关闭窗体。 例如:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// if disposed, close as usual
if (myControl == null || myControl.Disposed) return;
// disable the form so nothing can be done while
// were asynchronously disposing the form...
this.Enabled = false;
e.Cancel = true;
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(()=>myControl.Dispose())
.ContinueWith(a=>Close(), context);
}