gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:08:13 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com