0

我遇到了我在这里询问的问题的变体。而不是类扩展System.Windows.Form,我有一个类扩展System.Windows.UserControl,它没有FormClosing事件。

我考虑向Close用户控件添加一个方法,在该方法中我告诉本机线程停止。当它停止时,它会向用户控件引发一个事件,该事件会调用Dispose自身。这种方法的问题是Dispose从对象调用 dispose(自杀?)似乎是一种不好的做法,我不得不编写一个什么都不做的终结器(以避免双重处置),这感觉更糟......

建议?

更新:我的用户控件位于 extends 类System.Windows.Forms.ToolStripControlHost中,该类的实例位于主应用程序表单中。

4

1 回答 1

1

我会向用户控件添加某种方法并在表单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);
}
于 2012-05-16T20:16:36.450 回答