What does Process.Dispose() actually do?
In C# class Process
inherits from class Component
that implements IDisposable
and so I can call Dispose()
on any Process
object. Do I really have to? How do I know if I really have to?
Suppose I have the following code:
var allProcesses = System.Diagnostics.Process.GetProcesses();
var processesNames = processes.Select( p => p.ProcessName );
// output process names here
Now it looks like I have an array of Process
objects and I have craft a try-finally
to traverse the array and Dispose()
each object. That's definitely lots of extra code.
What does that Dispose()
do for Process
objects? Do I really need to Dispose()
every Process
object and how do I decide if I need to do so?
Solution 1:
Do I really need to
Dispose()
everyProcess
object and how do I decide if I need to do so?
Yes, you should dispose them. Note this text in the documentation for Process
:
A system process is uniquely identified on the system by its process identifier. Like many Windows resources, a process is also identified by its handle, which might not be unique on the computer. A handle is the generic term for an identifier of a resource. The operating system persists the process handle, which is accessed through the Handle property of the Process component, even when the process has exited. Thus, you can get the process's administrative information, such as the ExitCode (usually either zero for success or a nonzero error code) and the ExitTime. Handles are an extremely valuable resource, so leaking handles is more virulent than leaking memory.
So if you don't Dispose
them, you're potentially leaking the handles (until they're garbage collected - but the whole point of Dispose
is to allow early cleanup of resources)
Note, also, that the same documentation indicates that Process
overrides Dispose(bool)
- another clue that it actually does something when Dispose
is called.