Explain a critical error in Visual Studio 2010 and above, WinForms and WPF

Try putting the following code inside the Load event handler for WinForms or Loaded for WPF.

 Dim doc As New XmlDocument Dim nsmgr As New XmlNamespaceManager(Nothing) 'this line throws an exception 

The problem is that the exception is not thrown and the stack is corrupted. It can have different side effects, depending on the IDE - see below.

  • Affected IDEs: 2008, 2010, and 2012 (the ones I could check). 2010 resets the stack state and returns from sub / handler as if nothing had happened (but without resorting to other statements there). 2012 may warn the user about a failed application and attempt to run in compatibility mode . The next time after that, it works the same as 2010. 2008 generates an exception correctly, but only by default (AnyCPU). The porting of the platform platform to x86 again caused a problem in 2008.
  • The affected frames are WinForms and WPF. Console applications and ASP.NET seem to work fine..NET v2.0-4.5.
  • The affected scope is only a Load event. Including this code in a button makes it work.
  • Affected Assembly Configuration = Any. Tried Debug and Release by default.

Why do I consider this a mistake, because it can leave objects in an unstable state - they did not complete initialization, which is not the expected behavior. What is important is that no one will know that this happened because it does not cause an exception. Depending on your design, you may receive incorrect data in your database, which in the worst case can lead to serious consequences.

Does anyone have a good explanation why this could happen, and if there is a workaround?

+7
source share
1 answer

The problem is caused by the wow64 emulation level that comes into play when you target the x86 platform on an x64-based OS.
It swallows exceptions in the code that is responsible for triggering the Load event.
Thus, the debugger does not see an exception and cannot intervene in this situation.
This article seems to document well what is happening there,

This previous answer from Hans Passant (to which all loans and advances go) explains possible workarounds.
My preferred one is to move everything from the Form_Load event and put the problematic code in the form constructor. (Of course, I do not know if this is applicable in your case)

+2
source

All Articles