Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Dispose method will clear and compact the memory in .Net?

I have an idea about Dispose and Finalize method in .Net as laid out below. Is this correct?

Dispose : Implement IDisposable interface and remove unused/unmanaged code in the Dispose() method. The developer needs to call it manually if they want immediate removal or GC will dispose the resources when it is invoked.

Finalize : When GC invoked it will free the unused managed code and if IDisposable is implemented then it will call the Dispose() method to free up the unmanaged resources (normally).

Essentially, when we dispose the resources using the Dispose() method, will memory will be freed immediately and compacted (like the GC does)?

like image 397
Syed Avatar asked Oct 26 '25 17:10

Syed


2 Answers

The answer to your question is no: releasing the memory allocated for the object has nothing to do with calling the Dispose method. It happens in due course when the garbage collector gets to it.

Generally speaking, Dispose is intended for speeding up the release of external resources, such as file handles, semaphores, db handles, and other items often allocated by the operating system. If your object holds on to other IDisposable objects, it should dispose them in its call to dispose as well.

Finalizer, however, is different: it is called as part of garbage collection, and is intended for releasing external resources that have not been released during the dispose (presumably, because the user forgot to call Dispose). Finalizers must not call Dispose of other objects that your object may hold, because they are in the process of being garbage collected already.

like image 150
Sergey Kalinichenko Avatar answered Oct 29 '25 15:10

Sergey Kalinichenko


No. Calling the Dispose method directly or via a using statement will not cause memory to be freed.

Implementing IDisposable will just give your class a chance to clean up any unmanaged resources its holding onto.

like image 44
Andrew Kennan Avatar answered Oct 29 '25 14:10

Andrew Kennan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!