Do IDisposable objects get disposed of if the program is shut down unexpectedly?

前端 未结 6 1689
借酒劲吻你
借酒劲吻你 2021-01-17 07:31

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

6条回答
  •  时光说笑
    2021-01-17 07:52

    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.

提交回复
热议问题