C#的IDisposable处置 [英] C# disposing IDisposable

查看:219
本文介绍了C#的IDisposable处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释一下,如果你这样做会发生什么事情没有的Dispose 一些的IDisposable 实体的(按使用或直接的Dispose 调用)的?

Could someone explain what might happen if you don't Dispose some IDisposable entity (by using or direct Dispose call)?

这是否总是导致的内存泄漏,如果是,是 C#内存泄漏类同 C ++ 内存泄漏,在那里他们可以很容易导致崩溃或从这个角度来看?

Does this always result in a memory leak and if yes, are C# memory leaks similiar to C++ memory leaks, where they could easily lead to a crash or is C# sandbox safer from this point of view?

感谢您。

推荐答案

这完全取决于有问题的对象。

It completely depends on the object in question.

有<击>四五个原因,一个对象有可能实现的IDisposable

There are fourfive reasons that an object might implement IDisposable:


  1. 它拥有本地资源。结果
    。如果是这样,它的的通话的Dispose 在它的终结,因此,所有如果你忘了处理掉它是原生资源持续超过必要的。结果
    更长如果您创建大量的此类对象出现这种情况一次,不处理他们,你可能会耗尽本机资源。

  1. It owns native resources.
    If so, it should call Dispose in its finalizer, so all that happens if you forget to dispose it is that the native resources last longer than necessary.
    If you create lots of such objects at once and don't dispose them, you may run out of native resources.

它拥有管理对象是一次性的。结果
中的对象,它拥有也将属于这些类别之一;请参阅相关的类别。

It owns managed objects that are disposable.
The objects that it owns will fall also into one of these categories; see the relevant category.

它有一个持久的引用本身不会被释放自然(例如,它可以处理一个静态事件),结果
上的Dispose方法将清除此引用(例如,注销事件处理)结果
如果是这样,不是要求处置将导致它永远持续下去。

It has a long-lasting reference to itself that won't be freed naturally (eg, it handles a static event)
The dispose method would clear this reference (eg, unregister the event handler)
If so, not calling Dispose will cause it to last forever.

它继承了一次性的基类,如组件,但实际上并不需要进行处理。 (例如,的MemoryStream )结果
如果是这样,不是要求的Dispose 是无害的,除非类改变未来。

It inherits a disposable base class, such as Stream or Component, but doesn't actually need to be disposed. (eg, MemoryStream)
If so, not calling Dispose is harmless, unless the class changes in the future.

它执行其的Dispose 方法有所行动,人们应该在通话使用语句(如使用(Html.BeginForm(){...} )结果
。如果是这样,不处置的对象将打败它的整个目的,就是做这个动作。

It performs some action in its Dispose method that people should call in a using statement (eg, using (Html.BeginForm() { ... })
If so, not disposing the object will defeat its entire purpose, which is to do that action.

这篇关于C#的IDisposable处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆