Invoke
时,会收到ObjectDisposedException
异常。以下是演示该问题的示例代码:public partial class Form2 : Form
{
void Form2_Load(object sender, EventArgs e)
{
// Start a task that does an Invoke on this control
Task.Factory.StartNew(TaskWork);
// Sleep here long enough to allow the task that does the Invoke
// to execute to the point where it has:
// a. Posted the message and
// b. is waiting
Thread.Sleep(500);
// Cause ShowDialog to return by setting the DialogResult
DialogResult = DialogResult.OK;
}
void TaskWork()
{
// This call doesn't return, but instead throws an ObjectDisposedException
this.Invoke((MethodInvoker)(() => MessageBox.Show("Invoke succeeded")));
}
}
以下是来自主窗体Form1的调用代码,我从未关闭它:
public partial class Form1 : Form
{
Form2 m_form2 = new Form2();
void Form1_Load(object sender, EventArgs e)
{
// Call ShowDialog, but don't dispose it.
m_form2.ShowDialog();
// Cause the finalizers to run. This causes an AggregateException to be thrown
// due to the unhandled ObjectDisposedException from the Task.
GC.Collect();
}
}
我们深入研究了Microsoft的源代码,并发现异常是在调用DestroyHandle时创建的(如下所示)。ShowDialog在完成时将调用DestroyHandle。
来自source.NET\4\DEVDIV_TFS\Dev10\Releases\RTMRel\ndp\fx\src\WinForms\Managed\System\WinForms\Control.cs\1305376\Control.cs:
protected virtual void DestroyHandle() {
// ...
// If we're not recreating the handle, then any items in the thread callback list will
// be orphaned. An orphaned item is bad, because it will cause the thread to never
// wake up. So, we put exceptions into all these items and wake up all threads.
// If we are recreating the handle, then we're fine because recreation will re-post
// the thread callback message to the new handle for us.
//
if (!RecreatingHandle) {
if (threadCallbackList != null) {
lock (threadCallbackList) {
Exception ex = new System.ObjectDisposedException(GetType().Name);
while (threadCallbackList.Count > 0) {
ThreadMethodEntry entry = (ThreadMethodEntry)threadCallbackList.Dequeue();
entry.exception = ex;
entry.Complete();
}
}
}
}
// ...
}
问题:
为什么ShowDialog会销毁句柄(当我可能会重用这个窗体)?
为什么我会收到ObjectDisposedException,这非常具有误导性(因为它没有被处理)。 就像代码期望只有在对象被处理时才会销毁句柄一样(这也是我所期望的)。
这是否有效? 也就是说,我能在ShowDialog之后调用Invoke到控件上吗?
备注:
第二个.ShowDialog()会创建一个新的句柄。
如果在做完.ShowDialog()之后尝试进行Invoke,则会收到InvalidOperationException错误,指出“Invoke或BeginInvoke不能在控件上调用,直到窗口句柄已被创建。”。
如果在完成.ShowDialog()后访问Handle属性,然后进行Invoke,它将成功。
IsDisposed
属性后,仍然遇到InvalidOperationException
异常。我发现即使IsDisposed
为false,但在这种情况下Disposing
属性也为true。 - NiKiZe