tags:

views:

568

answers:

3

I have a C# app which uses a System.Diagnostics.Process to run another exe. I ran into some example code where the process is started in a try block and closed in a finally block. I also saw example code where the process is not closed.

What happens when the process is not closed?

Are the resources used by the process reclaimed when the console app that created the process is closed?

Is it bad to open lots of processes and not close any of them in a console app that's open for long periods of time?

Cheers!

+1  A: 

They will continue to run as if you started them yourself.

mannu
+1  A: 

A process is a standalone entity. Programatically creating a process is much the same as launching a process from your desktop.

The handle to a process you create is only returned for convenience. For example to access its input and output streams or (as you saw) to kill it.

The resources are not reclaimed when the parent process is killed.

The only time it is bad to open lots of processes is if you open so many that the CPU and RAM cannot handle it!

Declan Shanaghy
+4  A: 

When the other process exits, all of its resources are freed up, but you will still be holding onto a process handle (which is a pointer to a block of information about the process) unless you call Close() on your Process reference. I doubt there would be much of an issue, but you may as well. Process implements IDisposable so you can use C#'s using(...) statement, which will automatically call Dispose (and therefore Close()) for you :

using (Process p = Process.Start(...))
{
  ...
}

As a rule of thumb: if something implements IDisposable, You really should call Dispose/Close or use using(...) on it.

Duncan Smart
Note that calling Close on a process does not cause the process to exit.
Declan Shanaghy