Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process does not kill on form close

Tags:

c#

winforms

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

like image 820
Daryl Gill Avatar asked Dec 20 '22 12:12

Daryl Gill


2 Answers

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.

like image 188
Hans Passant Avatar answered Jan 11 '23 06:01

Hans Passant


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.

like image 28
Andrew Grinder Avatar answered Jan 11 '23 06:01

Andrew Grinder