You do know that calling TerminateProcess
to close an application is like jerking the power plug out of the wall to shut down your computer, right? It doesn't ask nicely, and it doesn't do the right thing. It just forcibly rips your process out of memory.
It therefore makes a good deal of sense that the Dr. Watson debugger is going to pop up—no correctly functioning application is going to request that it be terminated in such an unusual way. One of the threads that you're terminating was probably busy and didn't expect to have the rug ripped out from underneath it. It is, of course, not notified when you call TerminateProcess
. So there are all kinds of things that can go wrong here. Dr. Watson concludes that this has to be a symptom of a bug or some other problem, so it steps in to capture a crash dump.
The exit code you pass is irrelevant here. You can inspect it yourself after a process has exited, but it is not evaluated by Windows.
My suggestion is not to try and figure out what is keeping Dr. Watson from appearing sometimes, but rather to find a better way to close your application. If you had provided more details about your design and why you think you need to close the app in the first place, I could have made better suggestions. Right now, all I can suggest is to call Application.Current.Shutdown()
. That ensures that your application is shut down the right way, which will keep the debugger from being invoked. It is, however, still an irreversible action, so it should still do what you want.
In Win32 terms, since perhaps that's your native language, the correct way to shut down an application is to cleanly shut down all of the worker threads associated with your process first, and then call the ExitProcess
function. Notice the significance of the naming—exit is a normal action, terminate is not.