Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

process

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!

like image 895
MrDatabase Avatar asked Dec 08 '22 09:12

MrDatabase


1 Answers

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.

like image 54
Duncan Smart Avatar answered Dec 29 '22 01:12

Duncan Smart