A destructor (or finalizer) is not a place to place such code. It is designed to free up unmanaged resources. Destructors are called non-deterministic, so you cannot rely on any of your objects to be valid inside the destructor. And you cannot catch it in the debugger, because it is called in a separate thread, in special circumstances. In short, do not use destructors unless you know what you need.
The ideal way to register for application closure is to simply put the logging code at the end of the Main
method. You need to make sure that you catch and write down any exceptions that were thrown, and if so, you can write the end at the end of Main
.
There will be several edge cases where you cannot register a shutdown due to errors such as stack overflows. In these cases, you will need to rely on the logs of what happened before the error.
source share