c# - Process.Dispose() 实际上做了什么?

标签 c# .net idisposable

在 C# 中,class Process 继承自实现 IDisposableclass Component,因此我可以调用 Dispose()在任何 Process 对象上。我真的必须这样做吗?我怎么知道我是否真的必须这样做?

假设我有以下代码:

 var allProcesses = System.Diagnostics.Process.GetProcesses();
 var processesNames = processes.Select( p => p.ProcessName );
 // output process names here

现在看起来我有一个 Process 对象数组,我设计了一个 try-finally 来遍历该数组和 Dispose() 每个对象。这肯定有很多额外的代码。

Dispose()Process 对象做了什么?我真的需要 Dispose() 每个 Process 对象吗?我该如何决定是否需要这样做?

最佳答案

Do I really need to Dispose() every Process object and how do I decide if I need to do so?

是的,你应该处理它们。请注意 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.

因此,如果您不 Dispose 它们,您可能会泄漏句柄(直到它们被垃圾收集 - 但 Dispose 的全部意义在于允许尽早清理资源)


另外请注意,同一文档表明 Process 覆盖了 Dispose(bool) - 另一个线索表明当 Dispose 被调用。

关于c# - Process.Dispose() 实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16957320/

相关文章:

c# - WPF:将具有不同类型项目的多个级别添加到 TreeView

.net - ASP.NET MVC 4 捆绑和缩小

c# - Web 服务和轮询

c# - Print/Debug.Log 未在 Unity 控制台上显示输出

c# - SqlDataReader.GetString 和 sqlnullvalueexception

.net - 未触发 Oracle 登录触发器

c# - 在重新填充 IDisposable 对象之前是否必须处理它们?

c# - 注入(inject)存储库上的 IDisposable

c# - IsDisposed 是如何工作的?

c# - Amazon Web Services 解决方案不会在 Release模式下构建