I want to execute some code (clear up reso开发者_C百科ucrse) on termination my WinFormsApplication using Windows TaskManager. How can I do it? I am terminating my application using Process Tab of TaskManager.
If your application is forcibly closed I'm not sure there is a reliable way to ensure you clean up resources. I'm assuming your resources are non-standard ones that you, and not Windows, manage.
There are two possibilities. The first is to install a windows service application that watches your app and ensures its resources are cleaned up when your application is killed. This requires some inter-process communication and a fair amount of coding.
The second is to ensure resources are clean on application startup. Check to see if your resources are out there hanging around when you run, and clean them up before continuing execution.
Hookup the ApplicationExit event from your main form and do the cleanup there.
Edit: If you are closing the application through the task manager, there is no event that you can catch. These events are expecting normal termination processes.
Handle this event in your main app window:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
if(e.CloseReason == CloseReason.TaskManagerClosing) {
// clean up code
}
}
I am not sure and I haven't tried it. But my guess is that it should be possible by trapping some Win32 events. Try WM_CLOSE, CTRL_CLOSE_EVENT
The CriticalFinalizerObject might help you according to its description:
... the common language runtime (CLR) guarantees that all critical finalization code will be given the opportunity to execute, provided the finalizer follows the rules for a CER, even in situations where the CLR forcibly unloads an application domain or aborts a thread
精彩评论