简体   繁体   中英

Windows forms kill background process on app exit

I am making a simple windows form application in Visual Studio. But I have a problem when I want to close the app. When I right-click it from taskbar and close it, I can see background process still running in Task Manager.
How do I kill whole app?
I have paced this in first form that is opening when app starts:

     private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(!exit)
            {
                if (MessageBox.Show("Close the app?", "Simple App", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    exit = true;
                    Close();
                }
                else
                {
                    e.Cancel = true;
                    exit = false;
                }
            }
        }

I added Application.Exit(); on all forms in OnFormClosing event. And it is working good.

What you describe is the main problem with background processes. They just don't automatically end their work when the calling process is ended.

In essence you have 2 possible alternatives there both of which have a delay though (and have a possibility of not working depending on how stable your background processes are).

  1. Kill the process manually When you create the process you save its handler and then send a kill signal to it upon application exit. Like usual when you manually send a kill signal it can be that it takes some while to take an effect. And if if takes effect it can still happen that the process ignores it or ends at a state of process execution you don't want it to end

  2. Habe a kill flag within the process The process itself has a flag to which he reacts. When you kill the main application you set the flag to the "end me" setting and within the background process you check on each iteration it makes (or at least periodically) if the flag is set and if it is set just end the process from within.

In both cases you can optionally wait in the main application with a while loop and check if the process has ended correctly. Only problem here is that it CAN be depending on the exact implementation of the background process that it never ends as it just ignores the kill command.

Thus in essence it is possible to kill background processes from the main process BUT it probably will be a delayed kill AND it can be that it will not work.

In this case as you want the background process to end at application exit I would ask another question myself there: Are you sure that you want a BACKGROUND process there to be? As a foreground process just does automatically what you want: End at the end of execution of the main process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM