我应该什么时候在 .NET 中处理我的对象? [英] When should I dispose my objects in .NET?

查看:14
本文介绍了我应该什么时候在 .NET 中处理我的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一般代码,我真的需要处置一个对象吗?我可以在大多数情况下忽略它,还是在您 100% 确定不再需要它时始终处置它是个好主意?

For general code, do I really need to dispose an object? Can I just ignore it for the most part or is it a good idea to always dispose an object when your 100% sure you don't need it anymore?

推荐答案

在你用完它的那一刻就把它扔掉.一次性对象表示持有 CLR 本质上不知道的有价值资源的对象.因此,GC 也不知道资源,也无法就何时应该收集一次性对象并因此释放底层资源做出明智的决定.

Dispose of an object the instant your are done with it. Disposable objects represent objects holding a valuable resource which the CLR is not intrinsically aware of. Consequently the GC is also unaware of the resources and is unable to make intelligent decisions as to when it should collect a disposable object and hence free the underlying resource.

最终 GC 会感到内存压力并巧合地收集您的对象(仅此而已).如果您不以确定的方式处理对象,那么完全有可能进入几乎没有内存压力的资源匮乏状态.

Eventually the GC will feel memory pressure and collect your object by coincidence (nothing more). If you don't dispose of objects in a deterministic manner then it is completely possible to enter a resource starved state with almost no memory pressure.

这是如何发生的快速示例.让我们将底层资源视为 Win32 句柄.这些是非常有限且相当小的.您运行一个创建大量 Foo 对象的操作.Foo 对象实现 IDisposable 并负责创建和处置 Win32 句柄.它们不是手动释放的,而是通过不同的怪癖使其进入 Gen2 堆.这个堆很少被释放.随着时间的推移,足够多的 Foo 实例进入 Gen2 堆以占用所有可用句柄.因此,无论使用多少内存,都无法创建新的 Foo 对象.

Quick example of how this can happen. Lets think of the underlying resource as Win32 handle. These are very finite and fairly small. You run an operation that create a lot of Foo objects. Foo objects implement IDisposable and are responsible for creating and disposing of a Win32 handle. They are not manually freed and by a difference quirk make it into the Gen2 heap. This heap is freed fairly infrequently. Over time enough Foo instances make it into the Gen2 heap to take up all of the available handles. New Foo objects are consequently unable to be created regardless of how much memory is being used.

事实上,要释放句柄,需要在单个操作期间分配相当多的内存才能提供足够的压力来释放实例.

In fact to free the handles, it would take a rather large amount of memory to be allocated during a single operation to give enough pressure to free the instances.

这篇关于我应该什么时候在 .NET 中处理我的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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