Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

c# - What does Process.Dispose() actually do?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...