Showing posts with label Memory Management. Show all posts
Showing posts with label Memory Management. Show all posts

Saturday, 6 July 2024

Garbage Collector

 

What is difference between Finalize and Dispose

.Net  Framework provides two methods Finalize and Dispose for releasing unmanaged resources like files, database connections, COM etc. This article helps you to understand the difference between Finalize and Dispose method.

Dispose

It is used to free unmanaged resources like files, database connections etc. at any time.

Explicitly, it is called by user code and the class which is implementing dispose method, must has to implement IDisposable interface.

It belongs to IDisposable interface.

It's implemented by implementing IDisposable interface Dispose() method.

There is no performance costs associated with Dispose method.

 

Finalize

It can be used to free unmanaged resources (when you implement it) like files, database connections etc. held by an object before that object is destroyed

Internally, it is called by Garbage Collector and cannot be called by user code.

It belongs to Object class.

It's implemented with the help of destructor in C++ & C#.

There is performance costs associated with Finalize method since it doesn't clean the memory immediately and called by GC automatically.

 

What is Gc Garbage collector

in the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:

·        Enables you to develop your application without having to free memory.

·        Allocates objects on the managed heap efficiently.

·        Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.

·        Provides memory safety by making sure that an object cannot use the content of another object.