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

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

问题描述

对于一般code,我真的需要处理的对象?我可以忽略它在很大程度上还是一个好主意,总是处理的对象时,你的100%确定你不需要它anymroe?

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 anymroe?

推荐答案

处置对象的即时你用它做。一次性对象重新举行该CLR是没有本质上的认识的宝贵资源present对象。因此,该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会觉得内存pressure和巧合收集你的对象(仅此而已)。如果你不以确定的方式处置的对象则是完全有可能进入一个资源匮乏的状态,几乎没有记忆pressure。

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对象的操作。富对象实现IDisposable,并负责创建和处理一个Win32句柄。他们没有手动释放,由不同的怪癖,使之进入第二代堆。这堆被释放相当频繁。随着时间的推移足够美孚情况下使其进入第二代堆占用所有可用的手柄。新富的对象是因此不能不管多少内存被用来创建。

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.

在实际上以释放手柄,则需相当大量的存储器的单一操作期间要分配给足够pressure以释放实例。

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天全站免登陆