Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consequences of NOT properly implementing IDisposable

I am comfortable with how to implement IDisposable..

However I'm not clear as to the exact consequences of not implementing this properly. Is it a case that unmanaged resources will never be cleared thus causing memory leaks or will the memory eventually get recycled anyway, just not in a timely manner?

like image 552
AJM Avatar asked Jan 05 '11 16:01

AJM


2 Answers

It depends.

If the object in question fails to implement IDisposable, but does still implement a finalizer correctly, the resources will eventually get cleaned up.

However, if it doesn't properly implement a finalizer, AND it's wrapping an unmanaged resource, that resource will be leaked. This is more often a resource leak (ie: leaking a HANDLE stored as IntPtr) more than a traditional "memory leak" (though, of course, the object being pointed to does still use memory).

will the memory eventually get recycled anyway?

One point here... IDisposable has nothing to do with memory - it's about resources. These resources often use memory of their own, but implementing IDisposable does not cause your garbage collector to reclaim memory more quickly.

like image 122
Reed Copsey Avatar answered Sep 23 '22 21:09

Reed Copsey


It depends entirely on what te implementation is, of course.

An incorrect dispose on a SqlTransaction could lead to excessive long blocking, for example - impacting multiple machines and users. An incorrect dispose on a SqlConnection could cause connection saturation and inability to connect. These are not just memory (etc) issues.

IIRC a missing graphic (pen/brush/whatever) dispose was responsible for a VS crash bug - GC didn't happen because there was no memory pressure, so instead it simply saturated the GDI handles and broke.

An incorrect file/stream dispose could cause exceptions due to a file bring unavailable for reading/writing - potentially losing data.

With unmanaged resources not properly handled, anything is possible.

like image 23
Marc Gravell Avatar answered Sep 22 '22 21:09

Marc Gravell