Possible Duplicate:
What happens if I don't close a System.Diagnostics.Process in my C# console app?
As System.Diagnostics.Process
inherits from Component
which implements IDisposable
, should I always create a Process
with a using
block?
For example, this...:
using (var process = new Process())
{
process.StartInfo.FileName = "some process.exe";
process.Start();
process.WaitForExit();
}
...instead of this:
var process = new Process
{
StartInfo = { FileName = "some process.exe" }
};
process.Start();
process.WaitForExit();
I ask because I've rarely seen Process
appear in a using
block; for example the MSDN page for Process
does not use it. Having the use of the object initializer is helpful too.
If I should be using it, should I then go and 'retrofit' it to my existing codebase?
What might be the consequences if this were not done? (Assuming WaitForExit()
is being called correctly in each case.)
If you don't or cannot use using(), you should make sure you Dispose the process variable when it is no longer needed.
If you use the process variable in a class (instead of a Program or a method), then that class should implement IDisposable and then call _process.Dispose in its Dispose(bool) method:
void Dispose(bool disposing)
{
...
if (_process != null)
{
Dispose(_process);
}
}
If there is no _process field but only a process variable that you use in your method, you must dispose of it inside the method:
void MyMethod()
{
var process = ...
... use it here ...
process.Dispose();
}
The MSDN example is contrived. The program which opens a process handle is exiting as soon as it starts the process. When that program exits, any handles it opened are closed.
If you open a process handle, you should close it. The Process.Dispose override of Component.Dispose simply calls Process.Close. The using statement simplifies this.
来源:https://stackoverflow.com/questions/5857893/use-of-process-with-using-block