Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know about IDisposable Interface and it's use in .net but there is a question in my mind that If i am writing all managed code , does implementing IDisposable interface make any sense?

i know when and how to use Idisposible but my question is if i am writing all managed code say a simple class nothing expensive in it so if i implement IDisposable in this class and do some cleanup like freeing some global values, Does it make some sense?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
298 views
Welcome To Ask or Share your Answers For Others

1 Answer

No, you may not need to use IDisposble interface. However, it's recommended under certain circumstances (I might add later more as I remember :) ):

  1. You class has many objects and there are of lots of cross references. Even though its all managed, GC may not be able to reclaim the memory due to alive references. You get a chance (other than writing a finalizer) to untangle the references and break up the links the way you attached them. Hence, you are helping the GC to reclaim the memory.

  2. You have some streams open which are alive till the object of the class dies. Even though such implementations of files/network etc are managed, they go deep down to handles in Win32 mode. Hence, you get a chance to write a Dispose method where you can close the streams. The same is true for GDI objects, and some more.

  3. You are writing a class which uses unmanaged resources, and you want to ship your assembly to third parties. You better use disposable pattern to make sure you are able to free the handles to avoid the leakage.

  4. Thanks to supercat for this: Your class implements lots of event handlers and hooks them up to events. The objects of classes which expose the events, like Form etc., will not be freed up by GC since the implementations local to your class (maybe) are still hooked into those events. You can unhook those event handlers in Dispose; again helping GC.

Hmm... I can't remember more right now, but if the class is complex in its behaviours, you might want to rethink why you don't want implement IDisposable interface.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...