Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an object to null vs Dispose()

I am fascinated by the way the CLR and GC works (I'm working on expanding my knowledge on this by reading CLR via C#, Jon Skeet's books/posts, and more).

Anyway, what is the difference between saying:

MyClass myclass = new MyClass(); myclass = null; 

Or, by making MyClass implement IDisposable and a destructor and calling Dispose()?

Also, if I have a code block with a using statement (eg below), if I step through the code and exit the using block, is the object disposed of then or when a garbage collection occurs? What would happen if I call Dispose() in the using block anyay?

using (MyDisposableObj mydispobj = new MyDisposableObj()) {  } 

Stream classes (eg BinaryWriter) have a Finalize method? Why would I want to use that?

like image 586
GurdeepS Avatar asked Feb 22 '09 00:02

GurdeepS


People also ask

Does Dispose set object to null?

When an object implements IDisposable you should call Dispose (or Close , in some cases, that will call Dispose for you). You normally do not have to set objects to null , because the GC will know that an object will not be used anymore.

What does setting an object to null do?

If the reference is an instance variable, then setting it to null makes the object available for GC as long as there are no other references to it. However, if you set an instance variable to null, no other method in the class will be able to access that object using that variable.

Why do we have the Dispose () method?

The dispose pattern is used for objects that implement the IDisposable interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects.

What does Dispose () do in C#?

In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.


1 Answers

It's important to separate disposal from garbage collection. They are completely separate things, with one point in common which I'll come to in a minute.

Dispose, garbage collection and finalization

When you write a using statement, it's simply syntactic sugar for a try/finally block so that Dispose is called even if the code in the body of the using statement throws an exception. It doesn't mean that the object is garbage collected at the end of the block.

Disposal is about unmanaged resources (non-memory resources). These could be UI handles, network connections, file handles etc. These are limited resources, so you generally want to release them as soon as you can. You should implement IDisposable whenever your type "owns" an unmanaged resource, either directly (usually via an IntPtr) or indirectly (e.g. via a Stream, a SqlConnection etc).

Garbage collection itself is only about memory - with one little twist. The garbage collector is able to find objects which can no longer be referenced, and free them. It doesn't look for garbage all the time though - only when it detects that it needs to (e.g. if one "generation" of the heap runs out of memory).

The twist is finalization. The garbage collector keeps a list of objects which are no longer reachable, but which have a finalizer (written as ~Foo() in C#, somewhat confusingly - they're nothing like C++ destructors). It runs the finalizers on these objects, just in case they need to do extra cleanup before their memory is freed.

Finalizers are almost always used to clean up resources in the case where the user of the type has forgotten to dispose of it in an orderly manner. So if you open a FileStream but forget to call Dispose or Close, the finalizer will eventually release the underlying file handle for you. In a well-written program, finalizers should almost never fire in my opinion.

Setting a variable to null

One small point on setting a variable to null - this is almost never required for the sake of garbage collection. You might sometimes want to do it if it's a member variable, although in my experience it's rare for "part" of an object to no longer be needed. When it's a local variable, the JIT is usually smart enough (in release mode) to know when you're not going to use a reference again. For example:

StringBuilder sb = new StringBuilder(); sb.Append("Foo"); string x = sb.ToString();  // The string and StringBuilder are already eligible // for garbage collection here! int y = 10; DoSomething(y);  // These aren't helping at all! x = null; sb = null;  // Assume that x and sb aren't used here 

The one time where it may be worth setting a local variable to null is when you're in a loop, and some branches of the loop need to use the variable but you know you've reached a point at which you don't. For example:

SomeObject foo = new SomeObject();  for (int i=0; i < 100000; i++) {     if (i == 5)     {         foo.DoSomething();         // We're not going to need it again, but the JIT         // wouldn't spot that         foo = null;     }     else     {         // Some other code      } } 

Implementing IDisposable/finalizers

So, should your own types implement finalizers? Almost certainly not. If you only indirectly hold unmanaged resources (e.g. you've got a FileStream as a member variable) then adding your own finalizer won't help: the stream will almost certainly be eligible for garbage collection when your object is, so you can just rely on FileStream having a finalizer (if necessary - it may refer to something else, etc). If you want to hold an unmanaged resource "nearly" directly, SafeHandle is your friend - it takes a bit of time to get going with, but it means you'll almost never need to write a finalizer again. You should usually only need a finalizer if you have a really direct handle on a resource (an IntPtr) and you should look to move to SafeHandle as soon as you can. (There are two links there - read both, ideally.)

Joe Duffy has a very long set of guidelines around finalizers and IDisposable (co-written with lots of smart folk) which are worth reading. It's worth being aware that if you seal your classes, it makes life a lot easier: the pattern of overriding Dispose to call a new virtual Dispose(bool) method etc is only relevant when your class is designed for inheritance.

This has been a bit of a ramble, but please ask for clarification where you'd like some :)

like image 190
Jon Skeet Avatar answered Sep 28 '22 21:09

Jon Skeet