The online racing simulator
console exit problem
(8 posts, started )
console exit problem
i need to exit out of a console program i'm making nicely. meaning, i need to do some cleanup before actually quitting the program. for instance, i would need to close a mysql connection.

here's the code i have so far that i've found from other sites:
// test mysql area
MySqlCommand cmd = new MySqlCommand();
Object returnValue;
MySqlConnection connect = new MySqlConnection("<removed>");

// end area

/// <summary>
/// Starts up the program
/// </summary>
/// <param name="args">The args.</param>
static void Main(string[] args)
{
SetConsoleCtrlHandler(new ControlEventHandler(OnControlEvent), true);

try
{
Process[] pr;
pr = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
if (pr.Length > 1)
{
//Console.WriteLine("Only 1 instance of SingleInstanceTest is allowed...");
Environment.Exit(0);
}
else
{
//Console.WriteLine("There can be only 1...");
}
//Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Program p = new Program();
p.Config();
p.Setup();
p.Start();
p.Goooo();
}

public enum ConsoleEvent
{
CTRL_C = 0,
CTRL_BREAK = 1,
CTRL_CLOSE = 2,
CTRL_LOGOFF = 5,
CTRL_SHUTDOWN = 6
}

public delegate void ControlEventHandler(ConsoleEvent consoleEvent);

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern bool SetConsoleCtrlHandler(ControlEventHandler e, bool add);

public static void OnControlEvent(ConsoleEvent consoleEvent)
{

//connect.Close();
Console.WriteLine("Event: {0}", consoleEvent);
Console.ReadLine();
}

this code will actually work, but only if you use CTRL+C instead of the X in the corner of the console. the program will wait until the OnControlEvent processes. however, if you use the X in the corner, the program will Breakpoint there, but it will still exit itself, breaking past the breakpoint. i think that this is a drawback of the OS killing the thread, and not a real problem with the console program.

has anybody had to do a similar kind of thing for a console program, and would you be willing to post your code to try out?

also, it's possible for me to use this code now, just limit the closing of it to CTRL+C, but how do i get to my connect.Close(); from inside the OnControlEvent? connect is referenced at the top of the code snippet, which is outside of the main.
Seen as its a console app, You should make the global objects(MySqlConnection etc etc) static.
static MySqlConnection connect = new MySqlConnection("<removed>");

You will then have access to that from anywhere within the class. Im not too sure about your error tbh, but thats what you can do to make mysql global.
i guess i can revise my problem. i did some testing to see if, when the program is exited poorly (no cleanup, no disconnect), mysql still closes the connection. i watched the connections with mysql administrator, and did both kinds of close, the one that ran the connect.close() and the one where it wouldn't get run. both times the connection still closed by itself.

now i guess a new question. if the program is terminated in a poor way, would information get lost/corrupted when mysql terminates the connection, and not when the connect.close() is run? the data that gets written to the db is not volitile, as it would just get emptied and new data written to it next time.
This can be an issue if you are running your program inside a console window. If you just click the exit button to close the console window, then the process will just be shut down immediately and there is no way that I know of to intercept this event. The CLR then frees any resources attached to the process, so that's why the MySql connection closes, presumably regardless of whatever state its in. Whether it results in lose of data I guess depends on what the connection is doing...

Really console apps aren't designed to be run in their own little window, they're supposed to be run from the command line, and if do you run it like that then you can hook up a System.AppDomain.CurrentDomain.ProcessExit event to catch the process ending and do any clean-up operation you need. The other option is to setup your operations inside a mainloop in your program, and then when you want to exit just break out of the loop and you can do any cleanup before your reach the end of the main() method.
Unfortunately, command-line applications are command-driven applications, rather than event-driven applications. As such, you won't be able to intercept the close event easily. You'll either have to port to a simplistic event-driven, window-based application - or deal with the issue some other way.
Quote from DarkTimes :The other option is to setup your operations inside a mainloop in your program, and then when you want to exit just break out of the loop and you can do any cleanup before your reach the end of the main() method.

Wouldnt you be able to call methods from inside of main, And then when they are over. Return control back to the main method? Or am I thinking too much in the C++ world?
Yes, you could execute the loop in another method and do the cleanup in another method still. All I meant was something like this, there are a million ways to implement this.

static void Main()
{
// Setup program, load settings, init DB conn etc..

while(true)
{
// Respond to input, update database, do whatever...
// If exit is requested then...
break;
}

// Do any clean up stuff here before Main() returns.
}

Still, it doesn't solve the OP question, which is how to detect a console window has been closed. I'd agree with JamesF1 that it would be probably easier just to port the code into a Windows application, then you can very easily detect if a program is closing, you can even force it to stop closing if you want.
Signals are made available under the C standard library, which expose just the sort of events that you're after. I don't know if they're exposed under other languages, such as the .NET ones, however I'm sure it wouldn't be difficult to find out if you're motiviated.

For Windows check out these docs. If you're interested in the actual specs then wikipedia is rather helpful as will be the C/C++ compiler that you use (if you're using C/C++).

console exit problem
(8 posts, started )
FGED GREDG RDFGDR GSFDG