问题描述
可能重复:结果
的
由于的System.Diagnostics.Process
继承从组件
它实现了的IDisposable
,我就应该总是创建一个过程
与使用
阻止
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?
可能是什么后果,如果不这样做? (假设 WaitForExit()
正在在每种情况下正确调用。)
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.
如果您在使用过程一类(而不是一个程序或方法)变量,那么类应该实现IDisposable,然后调用_process.Dispose在它的Dispose(布尔)方法:
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);
}
}
如果没有_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();
}
这篇关于使用过程中,使用块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!