views:

66

answers:

2

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.

+2  A: 

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.

ctacke
Thanks ctacke. BTW great blog. It's helped several times. I'm new to this type of development. How do you programmatically detect if you have worker threads running? Does each new Form instance have it's own thread? I have several static Forms running in the app that I switch between, but I've used Form1 as my start and end point (aka: application "host") thinking that when I close this, all others will close as well.
radian21
You can programmatically detect threads, but it should be unnecessary here. In most cases the thread will be one you created in your code by calling new Thread (or possibly ThreadPool.QueueWorkItem). Forms do not create threads (unless you explicitly wrote code for it to).
ctacke
A: 

Your problem is that you have Form.MinimizeBox = true. Change it to false and the form will be closed when ok is clicked instead of minimized when x is clicked.

There are more things to consider in your question:

I override the Form1 FormClosed event

  • There is no FormClosed event for forms of type System.Windows.Forms.Form, only Closing and Closed.
  • You don't override an event. You override a virtual function from a base class or interface.
Johann Gerell