Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How garbage collection works on object references?

I am confused about garbage collection process on objects.

object A = new object();
object B = A;        
B.Dispose();

By calling a Dispose on variable B only, the created object will not be garbage collected as the object is still has referenced by A.

Now does the following code work same as above?

public static image Test1()
{
    Bitmap A = new Bitmap();
    return A;
}

Now I call this static function from some other method.

public void TestB()
{
   Bitmap B = Test1();
   B.Dispose();
} 

The static function Test1 returned a reference to the Bitmap object. The reference is saved in another variable B. By calling a Dispose on B, the connection between B and object is lost but what happens to the reference that is passed from Test1. Will it remain active until the scope of the function TestB is finished?

Is there any way to dispose the reference that is passed from the static function immediately?

like image 1000
kishore Avatar asked Aug 13 '10 17:08

kishore


1 Answers

Dispose does not garbage collect. You can't explicitly garbage collect a particular object. You can call GC.Collect() which requests that the garbage collector runs, but that's not the same. Calling Dispose doesn't even "disconnect" the object from a particular variable, in fact... while that variable remains live (up to the last time the JIT can detect that it will ever be read again) it will prevent the object from being garbage collected.

An object won't be garbage collected until it's no longer referenced by anything. Admittedly this can be earlier than you might think in some extreme cases, but you rarely need to worry about those.

It's worth being aware that Dispose and garbage collection are very different things. You call Dispose to release unmanaged resources (network connections etc). Garbage collection is solely to release memory. Admittedly garbage collection can go through finalization which may release unmanaged resources as a last resort, but most of the time you should be disposing of unmanaged resources explicitly.

like image 166
Jon Skeet Avatar answered Oct 25 '22 21:10

Jon Skeet