Unhandled NullReference exception when closing WPF application - c#

I'm getting an unhandled exception in my application when I close the last window:
An unhandled exception of type 'System.NullReferenceException'
occurred in PresentationFramework.dll
Additional information: Object reference not set to an instance of an
object.
This only occurs if, during the application's lifetime, I open a child window through a certain process that I have set up. The window exists in another assembly that is loaded at runtime dynamically with MEF, and then instantiated with Castle. If I then call a certain method, it creates a new STA thread and opens a WPF dialog window.
Some caveats:
This only happens on certain machines/environments (I'm not able to discern a pattern though)
I have an UnhandledException handler on the dispatcher for the application which catches all unhandled exceptions. This is not caught by that.
The call stack is:
PresentationFramework.dll!MS.Internal.Controls.ConnectionPointCookie.Disconnect()
PresentationFramework.dll!MS.Internal.Controls.ConnectionPointCookie.Finalize()
Has anyone seen this before, or would anyone know how to debug this? It's strange that there's no call stack and it happens right as the program is exiting.

Your question is devoid of details and the stack trace is short but gives lots of clues towards the underlying problem. Some visible facts:
the exception occurs on the finalizer thread, the reason the stack trace is so short. An unhandled exception in a finalizer is fatal, they'll always terminate the program. The reason that trying to use try/catch in your code had no effect.
a connection-point cookie is a COM term, you get one when you subscribe a COM event. That cookie needs to be used again when you unsubscribe the event, that happens in the finalizer. There is only one class in WPF that uses it, the WebBrowser control. The WPF class is a wrapper around Internet Explorer, a COM component.
the exception, while it has a managed exception name, is not caused by managed code. The finalizer already checks for null references, it is Internet Explorer that throws an unmanaged AccessViolationException under the hood. These are treated the exact same way by the CLR since they have the exact same cause, the finalizer doesn't otherwise do anything to make the distinction clearer. Unmanaged code is just as vulnerable as managed code to null pointers. More so, heap corruption is a very common cause.
the finalizer already catches all exceptions, an NRE is however a critical exception so it rethrows it, that's the end of your program.
Using WebBrowser is a liability, browsers in general are rather crash-prone. This is amplified when you use the control in your app, it runs in-process and doesn't have the kind of crash protection that Internet Explorer itself uses. So anything that goes wrong in the browser will directly affect the stability of your app, often with a very hard to diagnose crash reason since it is unmanaged code that bombs.
And such crashes repeat very poorly, the core reason that you trouble getting a repro for it yourself. The most common troublemakers in browsers are add-ins, ActiveX controls (like Flash) and anti-malware. You'll have extra trouble if you can't control the kind of web sites that are navigated, there are plenty that probe a browser for vulnerabilities intentionally.
There is one specific countermeasure you can use, call the control's Dispose() method when you no longer use it. Typically in the Window's Closing event handler. That will immediately unregister the COM event and trigger the crash, now you can catch it. Do strongly consider shutting down your program when that happens, you do have a dead corpse in your process that will turn in a zombie when you try to revive it.

I had the same problem in one of my applications and never found the real problem behind it. But I found a workaround for this application. At Closing event of the main window I implemented a loop that closed all other windows before. Then it worked. Maybe this could work for you too. If you find the reason it would be even better.

Related

WPF crash dump with original exception call stack and memory

I have a large WPF application which also uses C++ libraries for some functionality.
From time to time the application crashes due to a unhandled exception or access violation in the C++ code. EDIT: it sometime also crashes on the main thread due to unhandled C# exception.
I already employ the following handlers to log information about the crash:
DispatcherUnhandledException
TaskScheduler.UnobservedTaskException
AppDomain.CurrentDomain.UnhandledException
(EDIT: I register to these events very similar to this example: https://stackoverflow.com/a/46804709/2523211)
However, if I enabled dump file creation and these functions are reached (i.e. in an unhandled exception scenario) then the stack of the original exception has already unwound itself and there is no way for me to inspect the call stack along with the memory and threads at the moment of the error itself.
I can obviously see the stack trace itself in the exception that I get as argument to those handlers, but that is as far as that goes and I wish to see the state of my code when the exception was thrown.
(EDIT: The call stack just shows that I'm in a dispatcher frame and I cannot inspect the variables and other memory state of the application at the moment of the exception. I can use the data from the exception itself and see the call stack from it, but that's not enough to reproduce or really understand why the exception happened)
If I don't subscribe to those events then nothing changes, I still can't see the original call stack in the dump file. (EDIT: because I only get a call stack in the dispatcher)
I've also tried to set e.Handled = false but I think that that is the default value anyways.
Is there someway to indicate to WPF's dispatcher or maybe the issue is somewhere else, so that if an exception does happen, let it propagate all the way up such that when a dump is created for it, I will be able to have a helpful dump file?
What you are asking for is impossible to do within dotnet. You want to handle an exception without the stack being unwound, and dump your core for later analysis.
You can however do this outside of dotnet using the WinDbg APIs. Luckily, there is a wrapper for the WinDbg APIs called clrmd.
Just implement IDebugEventCallbacks.Exception and then call WriteDumpFile.
See https://github.com/microsoft/clrmd/blob/124b189a2519c4f13610c6bf94e516243647af2e/src/TestTasks/src/Debugger.cs for more details.
However, you should note. This solution would be attaching a debugger to production. Thus has the associated costs.
If you are just trying to collect information to solve the problem some options include
Use ProcDump https://learn.microsoft.com/en-us/sysinternals/downloads/procdump This can be configured to dump on 1st chance and 2nd chance exceptions, collecting multiple dump files if required i.e. allow app to keep running during 1st chance exceptions while capturing the app state in a dump file. Extensive configuration is possible via cmd line i.e. only handle specific exceptions etc, number of dump files to generate.
Use Time Travel Debugging feature of WinDbg, in this case you can walk backwards through your trace to find cause. This will severely degrade performance and if it takes more than several minutes to reproduce your issue these traces can quickly get very massive. If you copy the TTD folder out of WinDbg installation you can use it via command line to do a "ring mode" trace and specify a maximum buffer size which is more suitable if it takes a long time to reproduce issue, finding the options by running ttd.exe with no parameters.
Create a parent process that attaches as a debugger and will give you near full control over how you to decide to handle exceptions in the child process. Example here of creating a basic debugger

Exception control when release an application?

Possibly an obvious question to some but couldn't find a duplicate.
I'm packaging the final version of a Windows Forms solution I've been working on and am getting it ready for online distribution. What are the best practices when doing so? We've already had some trouble with packaging the installation file and have run into hurdles to test the program on different PCs, both 32 and 64-bit included.
More specifically, should "throw;" commands be commented out or left in the final release? Would this expose any of the inner workings of the solution itself?
Released application should not crash when exception occurs. You will want to inform the user, something went wrong and log your exception, but you do not want to crash! Informing user should be done in a friendly manner and not just by putting exception.ToString() into the message box.
It is a good practice to add Application.ThreadException or AppDomain.CurrentDomain.UnhandledException handlers to handle all exceptions in your Application. How exactly to do that, is answered in the following thread: Catch Application Exceptions in a Windows Forms Application
However, make sure that your application survives in a usable state, i.e. handle exceptions in a proper way for your application.
I usually add a preprocessor directive for handling exceptions on the application level, since I want them to trow while debugging. For example:
#if !DEBUG
Application.ThreadException += new ThreadExceptionEventHandler(MyHandler);
#endif
It should also be mentioned, that if you have code pieces where you anticipate that Exception might occur, such as network communication error, you should handle those pieces explicitly. What I am saying is, we should not completely forget about exception handling, just because we configured an unhandled exception handler on the application level.
Keep all of your exception handling intact.
Add an event to the starting form in the application, attaching to the Application.UnhandledException event. This will fire if an exception propogates up the stack.
This is the point to inform the user that the application has crashed. Log the error here and then abort gracefully.
Your point about revealing internals, thats up to you to decide. You can obfuscate the source code if you wish, but if you are releasing in Release build mode, and you are not providing the .PDB, then this is the first step.
Ultimately, the DLL / EXE can be decompiled anyway, so its up to you. Debug mode will reveal a lot more than Release mode, but not much more.
Ideally, you should be catching anything that's thrown higher with throw;. Carefully check your code and try to ensure that thrown exceptions are dealt with appropriately. Unhandled exceptions are logged - you can see this information in the Windows Event Viewer. Depending on what details you put in them, unhandled exceptions could give clues as to the inner workings of your application. However, I would suggest that unhandled exceptions are a poor source of information, and that anyone who wanted to know how your application worked could simply disassemble it, unless you've obfuscated it.
Some exceptions cannot be caught by surrounding code with try/catch blocks, so your application should also implement an unhandled exception handler. This gives you the opportunity to show the user an error message and do something with the exception - log it, send it to support, discard it, etc.

How to catch absolutely all exceptions / errors

I have a windows service application, running under WinXPe, which sometimes fails with an error and displays an message box to the user:
"The instruction at “”
referenced memory at “0x00000000”. The
memory could not be “read.” Press OK
to exit the program
If the user clicks "Ok" the service is restarting.
I have tried to catch all unhandled exceptions with registering a eventhandler at AppDomain.CurrentDomain.UnhandledException
in the handler I log the exception details and exit the application.
But the error I mentioned above is NOT handled from "UnhandledException".
The application is heavily multi threaded, using System.Threading.Timer and System.Threading.Thread. And it's using some third party libs, one of these libs are using native interop, I have no source of the native lib.
I tried to point out the error with an debugger attached, but the error doesn't show up ;)
The application has to run several days before the error occurs.
I need a way to handle such a error.
Thanks
See Vectored Exception Handling
This is part of windows SEH (Structured Exception Handling) and IIRC here is precious few errors that you could not at least be notified of in such a case.
You will probably want to write any handling code directly to the native WIN32 API (in unsafe/unmanaged code) and using pre-allocated (static?) buffers only, because there will be many things unreliable at that moment in time.
Beware of/stay away from threading, locking primitives, memory allocations, disk IO; preferrably use Windows default API's to, e.g. restart the process or produce a minidump and things like that
That error is not a managed exception. It's a lower level memory access violation. Essentially a NULL pointer access in native code.
This is something you're supposed to be completely protect from in managed code, so it's likely one of your native libraries or the way you're using them. If the error only appears after a few days of execution, you might be best off first going through any native library calls, checking their signatures and making sure you pass them data that makes sense.

Catching an Unhandled Exception Raised by an Unmanaged Sub-Process

Using C#'s System.Diagnostics.Process object, I start an unmanaged exe, that later starts yet another unmanaged exe.
The 2nd exe is causing an unhandled-exception that I'd like my application to ignore, but can't seem to.
I'm using a try/catch statement when I start the first process, but it doesn't seem to catch the exception raised by the 2nd process. When the exception occurs, the just-in-time debugger notifies me and halts my application until I manually click "yes" I want to debug or "no". Then my application proceeds.
The JIT debugger doesn't have source code for the 2ndprocess.exe that is throwing the exception. So, it doesn't tell me what the exception is. I don't really care what the exception is, I just want to know how to catch it and ignore it so my application doesn't get halted by it. By the time the exception occurs, the work is done anyway.
Can anyone offer some insight?
You should be properly handling the exception in the second executable. Your main program won't catch the exception because it isn't throwing one, it is executing something that is.
Edit:
Do you have access to the source of the second process (the one throwing the exception)? Your application shouldn't ever just crash. If the exceptional case gets handled correctly in the second process, you won't have this problem in your primary application.
Edit2:
Since you have access to the source (open source) I recommend you fix the bug. This will help you in two ways:
1) Your program will finally work.
2) You can say you contributed to an open source project.
And, as a special bonus, you get to help out a project you use frequently. Win/Win
Since you are using process.start to actually launch the application, the application creates a separate application domain. Capturing the exception from that application is not something that I believe will be possible, since more than likely the JIT dialog is coming up due to that failed process.
Although not a solution you could stop the dialog if needed, but that has issues of its own.

Handling rude application aborts in .NET

I know I'm opening myself to a royal flaming by even asking this, but I thought I would see if StackOverflow has any solutions to a problem that I'm having...
I have a C# application that is failing at a client site in a way that I am unable to reproduce locally. Unfortunately, it is very difficult (impossible) for me to get any information that at all helps in isolating the source of the problem.
I have in place a rather extensive error monitoring framework which is watching for unhandled exceptions in all the usual places:
Backstop exception handler in threads I control
Application.ThreadException for WinForms exceptions
AppDomain.CurrentDomain.UnhandledException
Which logs detailed information in a place where I have access to them.
This has been very useful in the past to identify issues in production code, but has not been giving me any information at about the current series of issues.
My best guess is that the core issue is one of the "rude" exception types (thread abort, out of memory, stack overflow, access violation, etc.) that are escalating to a rude shutdown that are ripping down the process before I have a chance to see what is going on.
Is there anything that I can be doing to snapshot information as my process is crashing that would be useful? Ideally, I would be able to write out my custom log format, but I would be happy if I could have a reliable way of ensuring that a crash dump is written somewhere.
I was hoping that I could implement class deriving from CriticalFinalizerObject and have it spit a last-chance error log out when it is disposing, but that doesn't seem to be triggered in the StackOverflow scenario which I tested.
I am unable to use Windows Error Reporting and friends due to the lack of a code signing certificate.
I'm not trying to "recover" from arbitrary exceptions, I'm just trying to make a note of what went wrong on the way down.
Any ideas?
You could try creating a minidump file. This is a C++ API, but it should be possible to write a small C++ program that starts your application keeps a handle to the process, waits on the process handle, and then uses the process handle to create a minidump when the application dies.
If you have done what you claim:
Try-Catch on the Application.Run
Unhandled Domain Exceptions
Unhandled Thread Exceptions
Try Catch handlers in all threads
Then you would have caught the exception except perhaps if it is being thrown by a third party or COM component.
You certainly haven't given enough information.
What events does the client say leads up to the exception?
What COM or third party components do you use? (Do you properly instance and reference these components? Do you pass valid arguments to COM function calls?)
Do you make use of any un-managed - un-safe code?
Are you positive that you have all throw-capable calls covered with try-catch?
I'm just saying that no-one can offer you any helpful advice unless you post a heck of lot more information and even at that we probably can only speculate as to the source of you problem.
Have a set of fresh eyes look at your code.
Some errors cannot be caught by logging.
See this similar question for more details:
StackOverflowException in .NET
Here's a link explaining asynchronous exceptions (and why you can't recover from them):
http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=c1898a31-a0aa-40af-871c-7847d98f1641

Categories