Strange uncatchable System.NullReferenceException in DeactivateMdiChild

Viewed 555

It is about C#/.NET Windows.Forms application.

I faced some weird behaviour of .NET - there is strange System.NullReferenceException exception inside .NET code and it is not possible to catch and handle such exception.

Here are exception details:

System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Form.DeactivateMdiChild()
       at System.Windows.Forms.Form.WmMdiActivate(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)
       at System.Windows.Forms.UnsafeNativeMethods.DefMDIChildProc(IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Form.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WndProc(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)
  InnerException: 

I tried to run my app with .NET 2.0 and with .NET 4.0 CLRs - it works the same way, it throws unhandled exception which is not possible to catch.

I tried to debug it with VS2012 and VS2019 - exception reported at the same location and it is impossible to catch or figure out a reason of exception.

When running release build of my app it reports unhandled exception here:

************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Windows.Forms.Form.DeactivateMdiChild()
   at System.Windows.Forms.Form.WmMdiActivate(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Here is a method which leads to that exception:

/// <returns>Returns true if we can close current workspace</returns>
private bool closeWorkspace()
{
    Trace.WriteLineIf(TrcLvl.TraceInfo, TrcLvl.TraceInfo ? string.Format("= FormMain.closeWorkspace( {0}: {1} queries )",  
        (this.document.DefaultWorkspace != null ? this.document.DefaultWorkspace.Name : "(null)"), this.MdiChildren.Length) : "");

    this.isClosingWorkspace = true;
    try
    {
        Trace.WriteLineIf(TrcLvl.TraceInfo, TrcLvl.TraceInfo ? string.Format(" - CloseWs: check if some of queries might be busy...") : "");
        foreach (Form mdi in this.MdiChildren)
        {
            if (!(mdi is FormQuery)) continue; // currently only FormQuery can be here, so this check is reserved for future version of app
            FormQuery frmQ = (FormQuery)mdi;
            if (frmQ.CheckIfBusy())
            {
                MessageBox.Show(Languages.TranslateFmt("Query[{0}] is busy!", frmQ.Query.Title),
                    Languages.Translate("Fail to Switch Workspace"), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
        }
        Trace.WriteLineIf(TrcLvl.TraceInfo, TrcLvl.TraceInfo ? string.Format(" - CloseWs: detach queries...") : "");
        List<FormQuery> toClose = new List<FormQuery>();
        foreach (Form mdi in this.MdiChildren)
        {
            if (!(mdi is FormQuery)) continue; 
            FormQuery frmQ = (FormQuery)mdi;
            frmQ.DetachQuery();
            toClose.Add(frmQ);
        }
        Trace.WriteLineIf(TrcLvl.TraceInfo, TrcLvl.TraceInfo ? string.Format(" - CloseWs: closing queries ({0} items)...", toClose.Count) : "");
        for (int i = 0; i < toClose.Count; i++)
        {
            FormQuery frmQ = toClose[i];
            Trace.WriteLineIf(TrcLvl.TraceInfo, TrcLvl.TraceInfo ? string.Format("  - CloseWs#{0}: closing [{1}]...", i, frmQ.Text) : "");
            toClose[i] = null;
            try
            {
                frmQ.Hide();
                //frmQ.Close(); 

                Thread.Sleep(100);
                frmQ.Dispose();
                Thread.Sleep(100);
            }
            catch (Exception exc)
            {
                Trace.WriteLineIf(TrcLvl.TraceError, TrcLvl.TraceError ? string.Format("  !!! CloseWs[#{0}].ERR.{1}\n\t{2}",
                    i, ErrorUtils.FormatErrorMsg(exc), ErrorUtils.FormatStackTrace(exc)) : "");
            }
        }
    }
    finally { this.isClosingWorkspace = false; }
    return true;
}

In VS debugger exception pops up here (in FormQuery.Designer.cs):

protected override void Dispose(bool disposing)
{
    try
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing); // <-- unhandled exception pops up here!
    }
    catch (System.Exception exc) // <-- this DOES NOT WORK AT ALL!
    {
        System.Diagnostics.Trace.WriteLineIf(TrcLvl.TraceError, TrcLvl.TraceError ? string.Format("  !!! FormQuery.Designer.ERR.{0}\n\t{1}",
            XService.Utils.ErrorUtils.FormatErrorMsg(exc), XService.Utils.ErrorUtils.FormatStackTrace(exc)) : "");
    }
}

As you can see - I tried to put try-catch statement there but .NET is not able to catch it!

Here is a pice from trace log:

20200709,104115.32 T1  = FormMain.closeWorkspace( Test 1: 6 queries )
20200709,104115.32 T1   - CloseWs: check if some of queries might be busy...
20200709,104115.32 T1   - CloseWs: detach queries...
20200709,104115.32 T1  Query[#6/Query_2_Errors].ReleaseData()
20200709,104115.32 T1  Query[#7/Query_4_Ini_prm].ReleaseData()
20200709,104115.32 T1  Query[#8/Query_5_func].ReleaseData()
20200709,104115.32 T1  Query[#9/Query_6_app].ReleaseData()
20200709,104115.32 T1  Query[#10/Query_7_OrderInfo].ReleaseData()
20200709,104115.32 T1  Query[#11/Query_8_Bom].ReleaseData()
20200709,104115.32 T1   - CloseWs: closing queries (6 items)...
20200709,104115.32 T1    - CloseWs#0: closing [Query_2_Errors]... <-- here it pops up "unhandled exception" UI
20200709,104131.89 T1  --- FormQuery[Query_4_Ini_prm].Activated()
20200709,104131.89 T1  --- FormQuery[Query_4_Ini_prm].ReportActive()
20200709,104131.89 T1  = FormMain.ReportActive( Query_4_Ini_prm )
20200709,104131.90 T1  = FormMain_MdiChildActivate --- #18 ---
20200709,104132.00 T1    - CloseWs#1: closing [Query_4_Ini_prm]...
20200709,104132.01 T1  --- FormQuery[Query_8_Bom].Activated()
20200709,104132.01 T1  --- FormQuery[Query_8_Bom].ReportActive()
20200709,104132.01 T1  = FormMain.ReportActive( Query_8_Bom )
20200709,104132.02 T1  = FormMain_MdiChildActivate --- #19 ---
20200709,104132.22 T1    - CloseWs#2: closing [Query_5_func]...

Here is stack-trace displayed in VS at the moment of exception:

System.Windows.Forms.dll!System.Windows.Forms.ContainerControl.Dispose(bool disposing) + 0x19 bytes 
System.Windows.Forms.dll!System.Windows.Forms.Form.Dispose(bool disposing) + 0x247 bytes    
> Query.exe!ABC.App.QueryNet.FormQuery.Dispose(bool disposing) Line 22 + 0x13 bytes C#
System.dll!System.ComponentModel.Component.Dispose() + 0x19 bytes   
Query.exe!ABC.App.QueryNet.FormMain.closeWorkspace() Line 1230 + 0x15 bytes C#
Query.exe!ABC.App.QueryNet.FormMain.mmiOpenWs_Click(object sender, System.EventArgs e) Line 1141 + 0xd bytes    C#
System.Windows.Forms.dll!System.Windows.Forms.ToolStripItem.RaiseEvent(object key, System.EventArgs e) + 0x5e bytes 
System.Windows.Forms.dll!System.Windows.Forms.ToolStripMenuItem.OnClick(System.EventArgs e) + 0x53 bytes    
System.Windows.Forms.dll!System.Windows.Forms.ToolStripItem.HandleClick(System.EventArgs e) + 0xa2 bytes    
System.Windows.Forms.dll!System.Windows.Forms.ToolStripItem.ProcessMnemonic(char charCode) + 0xe bytes  
System.Windows.Forms.dll!System.Windows.Forms.ToolStripDropDown.ProcessDialogChar(char charCode) + 0x51 bytes   
System.Windows.Forms.dll!System.Windows.Forms.Control.PreProcessMessage(ref System.Windows.Forms.Message msg) + 0x1b1 bytes 
System.Windows.Forms.dll!System.Windows.Forms.Control.PreProcessControlMessageInternal(System.Windows.Forms.Control target, ref System.Windows.Forms.Message msg) + 0x14e bytes 
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(ref System.Windows.Forms.NativeMethods.MSG msg) + 0x1f9 bytes   
System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(int dwComponentID, int reason, int pvLoopData) + 0x599 bytes  
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(int reason, System.Windows.Forms.ApplicationContext context) + 0x578 bytes  
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop(int reason, System.Windows.Forms.ApplicationContext context) + 0x65 bytes    
Query.exe!ABC.App.QueryNet.Program.Main(string[] args) Line 48 + 0x28 bytes C#
[Native to Managed Transition]  
[Managed to Native Transition]  
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x47 bytes  
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x9b bytes    
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x4d bytes   

And the strange thing - there are 6 MDI-child windows in workspace but it reports unhandled exception only for one of MDI childs (always on closing 1st or 2nd MDI child, never on closing other MDI-childs). All the rest of MDI childs are closed fine. I tried to change sequence of MDI childs (by its content) - no way, it is always reporting unhandled exception for 1st or 2nd MDI-child closing despite the content.

I searched internet for this - not found anything. I seen only a ref to possible reason that ActiveX might be used but here that is not the case. My FormQuery is very simple, there are only - Panel, SplitContainer, TextBox, DataGridView, StatusStrip, one ContextMenu - nothig more. So, it does not use any ActiveX components...

I tried to analyze .NET internals with Reflector - I cannot see any possible reasons of such exception.

Also tried to use Hide()+Close(), Hide()+Dispose(), tried to add Thread.Sleep(100) in closeWorkspace() method - no way, it reports exception anyway and it is completely uncatcable! :-(

I completely run out of idea - how to figure out why that exception is there?! Could you please advice - what also I can check to find out the reason of exception and fix it?

Thank you.

0 Answers
Related