什么是Process.Dispose()实际上做?上做、实际、Process、Dispose

2023-09-02 01:49:02 作者:赤羽业

在C#类工艺从继承类组件实现的IDisposable 键,这样我就可以叫的Dispose()任何进程对象。难道我真的有什么打算?我怎么知道,如果我真的有什么打算?

假设我有以下的code:

  VAR allProcesses = System.Diagnostics.Process.GetProcesses();
 VAR processesNames = processes.Select(P => p.ProcessName);
 //输出过程在这里的名字
 

现在它看起来像我有进程对象的数组,我有手艺一个尝试,终于穿越阵列和的Dispose()每个对象。这绝对是许多额外的code。

什么叫的Dispose()进程的对象?难道我真的需要的Dispose()每个进程对象,我怎么决定,如果我必须这样做?

解决方案   

我是否真的需要的Dispose()每个进程对象,我怎么决定,如果我需要做的这样的吗?

是的,你应该释放他们。注意在文档中该文本Process:

  酒店投诉变好评,掌握这7个沟通技巧就行了

一个系统过程,唯一标识,在系统上它的进程标识符。就像许多Windows的资源,过程也被标识为它的手柄,这可能不是在计算机上是唯一的。手柄是通称的资源的标识符。操作系统仍然存在的过程手柄,它是通过过程组件的手柄属性访问,即使当处理已退出。这样,就可以得到该进程的管理信息,如退出code(通常是零代表成功,非零错误code)和EXITTIME。句柄是一个非常宝贵的资源,所以泄漏手柄比内存泄漏更多毒力。

所以,如果你不这样做处置他们,你可能泄漏手柄(直到他们垃圾回收 - 但整点处置就是让资源早期清理)

请注意,同时,同一文件表明,进程覆盖的Dispose(布尔) - 另一条线索,这实际上做的的东西的时候处置之称。

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?

解决方案

Do I really need to Dispose() every Process 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.

 
精彩推荐
图片推荐