Close it with style?

uberamd

Member
Joined
Jan 22, 2007
Messages
9
Programming Experience
Beginner
I have a console application that every 10 minutes opens a connection to a mysql db, opens a file stream writer, modifies the db, modifies a log file, closes both the mysql connection and file stream, and pauses for 10 minutes before going at it again. Thats all working as intended.

However, the application can be closed say while the mysql connection and file stream reader is open, which I don't want. Is there a way to catch when the user tries to close the application and have it call a function that will do conn.Close() and s.Close() before exiting so i am not leaving those open?
 
Example using SetConsoleCtrlHandler.
VB.NET:
Imports System.Threading
Module Module1
    Declare Function SetConsoleCtrlHandler Lib "kernel32.dll" ( _
        ByVal HandlerRoutine As ControlEventHandler, _
        ByVal Add As Int32) As Int32
 
    Public Enum ConsoleEvent
        CTRL_C = 0
        CTRL_BREAK = 1
        CTRL_CLOSE = 2
        CTRL_LOGOFF = 5
        CTRL_SHUTDOWN = 6
    End Enum
 
    Public Delegate Sub ControlEventHandler(ByVal consoleEvent As ConsoleEvent)
 
    Public Sub OnControlEvent(ByVal consoleEvent As ConsoleEvent)
        Console.WriteLine("Event: {0}", consoleEvent)
        t.Abort()
        Console.WriteLine("Thread closing gracefully in 1000ms")
        Threading.Thread.Sleep(1000)
    End Sub
 
    Dim t As New Thread(AddressOf looping)
 
    Sub Main()
        SetConsoleCtrlHandler(New ControlEventHandler(AddressOf OnControlEvent), True)
        t.Start()
        Console.ReadKey()
        t.Abort()
        t.Join()
    End Sub
 
    Sub looping()
        Do
            Console.WriteLine("Thread - working.")
            Thread.Sleep(100)
        Loop
    End Sub
End Module
 
Back
Top