Use of Process with using block [duplicate]

空扰寡人 提交于 2019-12-05 01:44:57

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!