Search code examples
vb.netclassdispose

Finalize not called for publically declared class


I have a class that I need in many forms, so I have declared it in a module.

Module modTTS

    Public g_TTS As clsTTS

End Module

I have a Finalize method in this class:

Protected Overrides Sub Finalize()

    Stop'this is never called. I don't know why

    MyBase.Finalize()

End Sub

I do not explicitely destroy the class when my program ends. I just wanted to silently let it slip out of scope. Is that not valid? What might be the reason why the Finalize procedure is not called?

Thank you!

According to the suggestions, I have changed my class to this:

Public Class clsTTS : Implements IDisposable

Private _Synth As New SpeechSynthesizer
Private _bDisposed As Boolean = False

' Public implementation of Dispose pattern callable by consumers. 
Public Sub Dispose() Implements IDisposable.Dispose

    Dispose(True)
    GC.SuppressFinalize(Me)

End Sub

' Protected implementation of Dispose pattern. 
Protected Overridable Sub Dispose(ByVal uDisposing As Boolean)

    If _bDisposed Then
        Return
    End If

    If uDisposing Then
        ' Free any other managed objects here. 
        If Not _Synth Is Nothing Then
            _Synth.Dispose()
        End If
    End If

    ' Free any unmanaged objects here. 
    _bDisposed = True

End Sub

Solution

  • here's an example using the ApplicationContext Class - MSDN

    also, Finalize() might not be called before the application thread terminates, therefore, resources are never released.

    You should implement the IDisposable Interface - MSDN instead. and call .Dispose() method of your object on ApplicationExit.

    iDisposable is simple to implement, just add : Implements iDisposable to your Class declaration, and intellisense will add the necessary procedures.

    You can also dispose of /close objects in a FormClosing / FormClosed event.

    personally, i only use Shared members as functions, or to keep some string vars, but not objects.