Search code examples
c#.netasp.netgarbage-collectionstatic-methods

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?


Solution

  • I may be off, but you seem to have a misunderstanding of Dispose and garbage collection. An object will be garbage collected once all references to it are gone, in a non-deterministic way. Dispose will usually get rid of the unmanaged resources, so the object is ready to be garbage collected. In your first example, you Disposed the object, theoretically making it unusable, but it still exists on the heap and you still have a reference to it, both A and B. Once those go out of scope, the garbage collector may reclaim that memory, but not always. In example 2, a Bitmap A is placed on the heap, then you return a reference of it, and set B to that reference. Then you dispose it and B goes out of scope. At that point no more references to it exist, and it will be garbage collected at a later point.