views:

129

answers:

0

Hi,

So i have a program that needs to do some cleanup before it exits, even if it is a forced exit. I know, hitting the power button is a forced exit where no cleanup can happen, but that would cause other, bigger issues too.

The Program hooks into a number of events to take care of the cleanup. My issue is that this does not work properly when compiled in Debug mode and this does not work correctly when compiled in Release mode and run from within VS (F5). In release mode, run from the console or from the file manager, everything does what it is supposed to.

When trying to debug the application if the Handler routine is triggered I get a nice dialog saying vshost has failed, looking for solution to the problem...

What do I have to do to make this code work in debug and release mode?

EDIT

Error: Error

exact steps take: 1) Press F5 2) wait a seconds 3) Click the [X] in the console window 4) Error, see linked image above

class Program
{
    public enum CtrlTypes
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT,
        CTRL_CLOSE_EVENT,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT
    }

    static string conDB = "";

    [DllImport("Kernel32")]
    public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
    public delegate bool HandlerRoutine(CtrlTypes CtrlType);
    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
    {
        DatabaseAccess db = DatabaseAccess.Instance; //Issues Here

        // Cleanup code removed

        return true;
    }

    public static void ExitProcess(object sender, EventArgs args)
    {
#if DEBUG
        Debug("\n\n\nDebug Mode\nPress any key to continue...\n");
        Console.ReadKey(true);
#endif
    }

    static int Main(string[] args)
    {
        SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
        AppDomain.CurrentDomain.ProcessExit += ExitProcess;

        // App code removed

        return 0;
    } // End main


    static void Debug(string text)
    {
        #if DEBUG
            Console.WriteLine(text);
        #endif
    }
}