Unfortunately, there is no event that you can handle whenever a process is killed.
You can think about killing the process, for example, turning off the power to the computer - no matter what code you developed to run when the system shuts down, if the computer does not turn off gracefully or correctly, this code will not start.
When you kill a process using the task manager, it calls the Win32 TerminateProcess function, which unconditionally forces the process (including all its threads) to exit. All threads / processes are terminated and all pending I / O requests are canceled. Your program is really dead. The TerminateProcess function does not call the shutdown sequence provided by the CLR, so your managed application does not even have an idea of ββwhat was closed.
You suggest that you worry about disposing of objects whenever your application process terminates, but there are a few things worth pointing out here:
Always try to minimize the damage that may be caused. Dispose of your objects as soon as possible when you are done with them. Do not wait later. At any point in time when your program process ends, you should only store a minimum number of objects, which will be less likely to leak.
The operating system typically cleans and releases most of these resources (i.e., processes, etc.) upon completion.
Finally, it goes without saying that completing the process in this way is indeed an exceptional condition - even if some resources flow, what can be expected. You should not close the application this way more than you should kill the necessary Windows system processes (even if you can work as an administrator).
If this is your usual plan to close the console application, you need to find another plan .
source share