Home ยป .net internals

.net internals

Determinism in Dispose and Finalize Execution Timing

I get a surprising number of questions about when objects are disposed or collected. Usually people will have some limited logic to cleanup their objects (releasing file handles, removing references to large objects, etc.), and they don’t know when this logic will execute. Here is a little bit of insight into when objects are disposed and finalized. (If you are looking for more information about Disposable and Finalizable patterns, check this post)

When Does Dispose Execute?

The Dispose method on an object is only executed when it is called by the application. What I mean by that, is the CLR does not automatically call Dispose on your objects. If you don’t call dispose, it can result in a memory leak that does not get cleaned up until the process exits.

This doesn’t mean you necessarily have to call Dispose() explicitly. In C#, there are a number of times that Dispose() is called implicitly:
Read More »Determinism in Dispose and Finalize Execution Timing

Be Kind to Your GC: Examining IDisposable and Finalize Patterns

Through my discussions with various developers, I have noticed a common theme when it comes to disposing objects. Most developers are confused, or at least unclear, on why and when to use dispose and finalize.

Let me start off with this: The purpose of dispose and finalize is the same… to improve the performance of the application and the host system. You don’t need to implement either. When the GC runs, unused managed memory will be reclaimed. When your process exits, the entire process’s virtual memory will be released. When the system re-boots, any open native handles will be closed. Dispose and finalize are two patterns that make it easier for your application to be a “good citizen,” releasing memory as soon as it is no longer needed and closing handles as soon as you are done with them.
Read More »Be Kind to Your GC: Examining IDisposable and Finalize Patterns