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?
The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
// If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. private void Dispose(bool disposing) { // Check to see if Dispose has already been called.
Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
There is a simple guideline: if you have finished with an object whose type implements IDisposable then call Dispose() on it; you should use a using block to do this.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With