Daryl Gill
Daryl Gill

Reputation: 5524

Process does not kill on form close

I have just built version one of my testing application using Windows Forms. I have noticed that when running the application, it runs completely fine no hitches, exactly like the debug view. When it comes to closing the application I have noticed that the actual executable/process name hangs within Task manager and does not correctly close.

Upon further inspection I have noticed that when calling another form without hiding the previous form, a new process is spawned (kinda expected). When closing the new form (containing a few text boxes, labels and a DataGridView) the newly spawned process does not kill it's self, but remains. Then closing the main window the window disappears from the taskbar/view, but still, the processes remain active using 8,268k - 8,308k Memory

Task Manager

    private void ClientSearch_Click(object sender, EventArgs e)
    {
        ClientSearch Clientsearch = new ClientSearch();
        Clientsearch.Show();
    }

enter image description here

Upvotes: 5

Views: 10939

Answers (2)

Hans Passant
Hans Passant

Reputation: 942308

Standard explanations for this behavior:

  • Hiding your main window when you display another window and forgetting to unhide it. There is no visible window anymore, nor can the user do anything to unhide it, but your app keeps motoring of course.

  • Starting a thread and not making sure that it is terminated when the main window closes. Setting the thread's IsBackground property to true is a workaround for that.

  • Calling Application.DoEvents() in your code. A very dangerous method that permits you to close the user interface but doesn't stop the loop in which it was called so the main thread of your app does not exit either.

This kind of problem is readily visible as well when you debug your app. You might have gotten in the habit of using the red rectangle on the toolbar (aka Debug + Stop Debugging) to force the debugger to quit. The Debug + Windows + Threads debugger window can provide insight into the cause of the last two bullets. Or you can use Tools + Attach to Process to attach the debugger to a zombie process.

Upvotes: 8

Andrew Grinder
Andrew Grinder

Reputation: 605

Call

Application.Exit();

on form close/closing.

Your applications should only be creating one process per run. A new form should not be creating a new process.

Upvotes: 5

Related Questions