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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With