What happens if the program exits unexpectedly (either by exception or the process is terminated)? Are there any situations like this (or otherwise) where the program will t
Yes, there are such situations. For example, calling TerminateProcess
, calling Environment.FailFast
, or encountering an internal CLR error will all cause the process to exit without running any additional code. In such situations, the best thing you can do is say "oh well".
Even if the process doesn't exit unexpectedly, calling Dispose
is a manual action. It's not something done through the runtime, except when an object implementing a finalizer that calls Dispose
is garbage collected. Therefore, forgetting to wrap a disposable in a using
or causing a memory leak that keeps the object alive is another way Dispose
may never be called.
The only reliable cleanup is performed by the operating system when a process exits -- all open handles to system objects are closed. When the last handle is closed, whatever cleanup implemented in the OS or a driver happens. If this cleanup code is not part of a driver but is supposed to be called by a user process, all you can do is make your code as robust as possible, or implement a watchdog process that handles cleanup for you.