我昨天在调试 Windows 窗体应用程序时发现了一个有趣的行为,请参考以下代码:
bool enter = false;
Debugger.Break();
if (enter) // Force to enter the if clause, read next comment
{
bool a = false; // Bypass previous IF check in debug using 'Set Next Statment (CTRL-SHIFT-F10)' here
// Will throw null reference exception
// If I don't use invoke everything works fine
Invoke(new MethodInvoker(() =>
{
a = true;
}));
}
因此,如果我强制输入不应该在方法上下文中输入的 IF 子句,并且代码具有使用 IF 子句中的任何对象的 Invoke 委托,它将引发空引用异常。
异常堆栈跟踪:
at WindowsFormsApplication2.Form1.Test() in c:\WindowsFormsApplication2\Form1.cs:line 26
at WindowsFormsApplication2.Form1.Form1_Load(Object sender, EventArgs e) in c:\WindowsFormsApplication2\Form1.cs:line 16
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
似乎该对象甚至没有在方法上下文中创建,但它仅在我有 Invoke 时发生,否则它将起作用。
有谁知道异常的根本原因是什么以及为什么它与一个尚未调用的 Invoke 方法有关?