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

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)?


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.


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.


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.

链接地址: http://www.djcxy.com/p/9238.html

上一篇: 在C#中实现IDisposable

下一篇: 调用Dispose方法将清除并压缩.Net中的内存?