3
votes

I have idea about Dispose and Finalize method in .Net as following. Please correct me if I am wrong.

Dispose : Implement IDisposable inferface and remove unused/unmanaged code in Dispose method. 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 Dispose method to free up the unmanaged resources(normally).

The question is: When we dispose the resources using Dispose method, memory will be freed immediately and compacted(as GC doing)?

3

3 Answers

5
votes

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.

2
votes

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.

1
votes

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

You are somewhat incorrect here. When you say "it will call Dispose", if you are referring to the GC itself, then, no, it does not "automatically" call Dispose for you. It is your job as the programmer to do cleanup in both the Dispose and Finalizer methods.

This MSDN writeup here demonstrates the typical disposal pattern.

The question is: When we dispose the resources using Dispose method, memory will be freed immediately and compacted(as GC doing)?

No, calling Dispose does not free heap memory. The heap memory is not released until the GC runs and performs the cleanup.