如果IDisposable的被cascadingly应用?IDisposable、cascadingly

2023-09-03 11:00:51 作者:后来烂人醉

这是一个相当基本的问题,但我仍然与它挣扎了一点。

This is a rather basic question, however I'm still struggling with it a little.

IDisposable的实现,如果要启用对象的用户,以释放潜在的资源(例如,插座等)之前的对象是最终垃圾收集。

IDisposable is implemented, when you want to enable the user of an object to free underlying resources (e.g. sockets etc.) before the object is eventually garbage collected.

当我有持有的DbConnection(实现IDisposable),就我的课需要实现IDisposable也和链调用下到的DbConnection或任何其他IDisposable的对象,它拥有的一类?否则DbConnections资源才会被释放时,我的课是GarbageCollected,从而降低它引用的连接和GC将完成的DbConnection。

When i have a class that holds a DbConnection (implements IDisposable), does my class need to implement IDisposable too and chain the call down to the DbConnection or any other IDisposable objects it owns? Else the DbConnections resources will only be freed when my class is GarbageCollected, thereby drops it reference to the connection and GC will finalize the DbConnection.

推荐答案

是的,您总是实现IDisposable如果你控制处置的对象。 始终。如果你不知道你的code不会打破,但它违背了处置的对象,如果你不这样做的目的。

Yes, you ALWAYS implement IDisposable if you control disposable objects. ALWAYS. Your code won't break if you don't, but it defeats the purpose of having disposable objects if you don't.

有关GC优化的一般规则是:

The general rule for GC optimization is:

在控制不是由GC管理必须实现一个终结器(一般应实现IDisposable和)对象的任何类。这就是顶级一次性类通常来自于 - 他们通常控制句柄窗口,插座,互斥体,或你有什么 在该实例化一个IDisposable的成员的所有类应该实现IDisposable本身,并妥善处理其成分()。 在任何函数实例化一个IDisposeable对象应该正确处理()它完成它在使用时。别让它只是辍学的范围。

这些规则可能弯曲或如果你正在写一个应用程序为自己,而是分配code时,别人对你应该是专业和遵守规则的忽略。

These rules may be bent or ignored if you're writing an application for yourself, but when distributing code to others you should be professional and follow the rules.

这里的逻辑是,当你在GC的观点之外控制内存的GC发动机不能恰当地管理内存使用情况。在您的.NET堆,例如,你可能只是有一个4个字节的指针,但在管理土地,你可以有200 MB的内存被指向。 GC的引擎将不会尝试,直到你有几十收集这些,因为所有它认为是几个字节;而在现实世界中,它看起来很像一个内存泄漏。

The logic here is that when you control memory outside the view of the GC the GC engine can't properly manage your memory usage. On your .NET heap, for example, you may just have a 4-byte pointer, but out in unmanaged land you could have 200 MB of memory being pointed at. The GC engine wouldn't attempt to collect these until you have several dozen, because all it sees is a few bytes; while in the real world it looks a lot like a memory leak.

因此​​,规则是,非托管内存应该得到立即释放,当你用它做(了IDisposable链可以实现这个要求),而管理的内存被释放了,每当它得到解决它的GC引擎。

Therefore, the rule is, unmanaged memory should get freed immediately when you're done using it (the IDisposable chain does this for you), while managed memory gets freed by the GC engine whenever it gets around to it.