In the Program.cs file of the .Net CF 3.5 WinForms program I've written, I launch the app by instantiating a new instance of Form1.
Application.Run(new Form1());
When I want to close/exit the application, I override the Form1 FormClosed event so that I can ensure exiting the application.
// In Form1 code-behind
private void OnFormClosed(object sender, EventArgs e)
{
Application.Exit(); // Doesn't kill process
}
When this code runs, I want the app to disappear from the screen (close) and I want the process it was running as to die. The app closes (disappears), but unfortunately, the process (we'll call it app.exe) is still running indefinitely. When I start the app again and close it, it spins up another app.exe process, etc. So the process is never dying and more are being created eating memory.
How can I ensure this process is being killed when I close/exit the app? Thanks.
First, you should not have to overide OnFormClosed to get the behavior you're after. Just closing the Form passed in to Application.Run will cause the app's message pump to exit and should cause the process to end. For Windows Mobile you should set the ShowMinimize property of the Form to false
to prevent it from just being minimized - you should have a (OK) in the upper right, not an (X).
If the process does not exit when this Form closes, then the culprit 99.99% of the time is that you have a worker thread that is still running preventing the process from closing. Make sure all of your Threads have IsBackground
set to true
(for CF 3.5) and as a precaution, all of your threads should also have some form of exit notification or flag. Don't rely of the process terminating to tear them down for you.