General Rule for Using IDisposable

EDIT: This question is a duplicate . What is the difference between managed and own resources when disposing? (.NET) and many others. Please answer others if you have something to add.


In accordance with the Framework Development Guide by Krzysztof Kvalina and Brad Abrams, a type containing instances of one-time types must implement IDisposable.

Is there any other general rule when it is best to use IDisposable?

+4
source share
6 answers

Deploy IDisposable if you have a class that wraps an unmanaged resource or when your class has a field that implements IDisposable.

+11
source

When you need to free unmanaged resources, run IDisposable .

+4
source

From MSDN: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of the object can call this method when the object is no longer needed.

+2
source

Whenever you allocate resources to be released, such as files, descriptors, etc. For example, if you use Win32 resources (which do not implement IDisposable), you must implement IDisposable to release them.

+1
source

I usually implement IDisposable every time I need to clear items. For me, this is when writing code that abstracts the database / network / file systems.

He simply marks the items ready for the garbage collector, rather than waiting for him to try to do it himself.

+1
source

IDisposable is one of the core programming tools against .Net memory leaks. Although the documentation suggests that it should be used for external resources, I widely use IDisposable to release internal resources, such as pointers to parent classes.

It is fairly easy to demonstrate this requirement by creating two mutually referenced classes, i.e. foo and bar. foo refers to a bar and vice versa. When foo falls out of scope, the GC sees that the bar is still referencing it, so it is not going to (and vice versa). No memory is collected.

This is the same problem style that EventHandlers invokes, where this link is not issued when the form is closed, if it is not explicitly released, or the WeakEvent model is not implemented.

I would suggest that the best practice is to use the C ++ programming model, in which you cleanse yourself after using Dispose if you are not sure if the GC can work for you.

+1
source

All Articles