views:

94

answers:

4

My application consists of main message loop (GUI) and threads (Task.Factory).

In the threads I call some 3rd party applications with var p = new Process();

But when I invoke Application.Exit(); in the message loop - I can see that the processes, that were started in the threads are still in the memory and are being executed.

So the question is - how to kill all the threads and Processes right after Application.Exit(); has been invoked?

UPD:

old:

p.WaitForExit();

new:

while (!p.WaitForExit(1000))
{
    if (FlagToExit)
    {
        p.Kill();
        return;
    }
}
+1  A: 

Handle the Application.ApplicationExit event.

Mark Cidade
So I just need to create some boolean flag that i need to observe in the threads and when it becomes true (i will assign it true on `Application.ApplicationExit` event) - then Terminate processes?
zerkms
I've added update, about how I expect to implement it. Please criticize it.
zerkms
What you said should work.
Mark Cidade
+1  A: 

Process are created independent of the parent process.

The best solution is to create a signal for the child processes and have them exit when it is signalled, gracefully shutting them down.

If the processes are outside of your control, then you'll have to use Process.CloseMainWindow and Process.Kill to kill them when your parent process is ready to exit.

Stephen Cleary
Why won't `Process.Kill` work?
Steven Sudit
It would. I had done a search using the traditional name of `Terminate`, so I missed the `Kill` method. Answer updated.
Stephen Cleary
A: 

Create a class calling the process and terminate it on it's dispose.

blez
+5  A: 

Simply try this

when you create a thread make it background thread

Thread.IsBackground = true;

and on Application.Exit();

all thread will be closed

shrikant.soni
-1: This does not terminate child processes, which is half of the op's question.
Stephen Cleary