Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

c# - IDisposable Interface

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...