Thursday, October 14, 2010

Closing the MS Access Session with Brute Force!

It can be tricky to kill a Microsoft Access database session by simply just closing it. The code below demosntrates how to close the application instance and release it entirely from memory using the Marshal technique.

BRUTE FORCE:


''' <summary>
    ''' Close and destroy on exit
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function CloseDB() As Boolean
        Try
            ' Close the database
            m_DaoDB.Close()
            ' Quit the application
            m_AccApp.Quit(Access.AcQuitOption.acQuitSaveAll)
            ' Marshal close just in case
            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_AccApp)
            ' Destroy the main variables
            m_AccApp = Nothing
            m_DaoDB = Nothing
        Catch ex As Exception
            ' Close the database
            m_DaoDB.Close()
            ' Quit the application
            m_AccApp.Quit(Access.AcQuitOption.acQuitSaveAll)
            ' Marshal close just in case
            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_AccApp)
            ' Destroy the main variables
            m_AccApp = Nothing
            m_DaoDB = Nothing
        End Try
    End Function