MrDatabase
MrDatabase

Reputation: 44455

What happens if I don't close a System.Diagnostics.Process in my C# console app?

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!

Upvotes: 5

Views: 3464

Answers (3)

Duncan Smart
Duncan Smart

Reputation: 32068

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.

Upvotes: 14

Declan Shanaghy
Declan Shanaghy

Reputation: 2335

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!

Upvotes: 1

mannu
mannu

Reputation: 793

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

Upvotes: 1

Related Questions