本文介绍了什么是Process.Dispose()实际上做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

假设我有以下的code:

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

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

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

解决方案

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

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


请注意,同时,同一文件表明,进程覆盖的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?

解决方案

Yes, you should dispose them. Note this text in the documentation for Process:

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.

这篇关于什么是Process.Dispose()实际上做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:25