Just Say No to Finalization!

I am working with some classes that wrap unmanaged APIs, so I have to be concerned with releasing the resources associated with these APIs – e.g., the IDisposable interface. I was a little confused about the distinction between Dispose() and Finalize(), and in my research I found this article by Brent Rector of Wintellect:

In a worst-case scenario, your object's Finalize method won't run until your process terminates gracefully. (Actually, the real worst case is that it never runs at all because the process terminates abnormally.) Shortly thereafter, non-memory resources will be released anyway, so the Finalize method served no real purpose other than to keep the application from running as fast as it otherwise could.

Just say No to Finalize methods!

It's a good point. In a true worst case scenario – unhandled exception time – you won't get any benefit from Finalize. So, given the (evidently) large performance penalty of Finalize, why bother? I tend to agree. However, the best practice according to Microsoft is, if you implement IDispose, you should also implement a Finalizer:

Private _IsDisposed as Boolean = False
''' 
''' public Dispose method intended for client use
''' 
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(False)
GC.SuppressFinalize(Me)
End Sub
''' 
''' common Dispose method; can be called by client or the runtime
''' 
Protected Overridable Overloads Sub Dispose(ByVal IsFinalizer As Boolean)
If Not _IsDisposed Then
If IsFinalizer Then
'-- dispose unmanaged resources
End If
'-- disposed managed resources
End If
_IsDisposed = True
End Sub
''' 
''' called by the runtime only, at garbage collection time
''' this protects us if the client "forgets" to call myObject.Dispose()
''' 
Protected Overrides Sub Finalize()
Dispose(True)
End Sub

It's all rather contradictory.

Read more

Stay Gold, America

We are at an unprecedented point in American history, and I'm concerned we may lose sight of the American Dream.

By Jeff Atwood · · Comments

The Great Filter Comes For Us All

With a 13 billion year head start on evolution, why haven't any other forms of life in the universe contacted us by now? (Arrival is a fantastic movie. Watch it, but don't stop there - read the Story of Your Life novella it was based on

By Jeff Atwood · · Comments

I Fight For The Users

If you haven't been able to keep up with my blistering pace of one blog post per year, I don't blame you. There's a lot going on right now. It's a busy time. But let's pause and take a moment

By Jeff Atwood · · Comments

The 2030 Self-Driving Car Bet

It's my honor to announce that John Carmack and I have initiated a friendly bet of $10,000* to the 501(c)(3) charity of the winner’s choice: By January 1st, 2030, completely autonomous self-driving cars meeting SAE J3016 level 5 will be commercially available for passenger

By Jeff Atwood · · Comments