I developed an application that does some operations like restoring network adapter settings on closing the application event. The app is written in c# 4.0 under win 7 64 bit and it's using WinAPI to catch the "console closing event".
The app is throwing "An unhandled exception of type 'System.NullReferenceException' occurred in Unknown Module." when I close it, and, in my opinion is due to the fact that, in that closing console event I do some operations. Using setConsoleCtrlHandler we can catch the "closing console app " event and we have a time window of about 1-2 seconds to do our operations, but sometimes this 1-2 seconds aren't enough to complete all I have to do in this method. The method is taking less then 1 sec to finish. This is the code I'm using to catch the closing event and the operations I'm doing when the event is triggered:
//WinAPI method that catches the close event
static class NativeMethods
{
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
public static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
// Put your own handler here
switch (ctrlType)
{
case CtrlTypes.CTRL_CLOSE_EVENT:
Console.WriteLine("Program being closed!");
try
{
//do stuff
}
catch(Exception ex)
{
Console.WriteLine("FAILED");
}
break;
}
return true;
}
}
//In Program.cs I register to catch the window events:
NativeMethods.SetConsoleCtrlHandler(new NativeMethods.HandlerRoutine(NativeMethods.ConsoleCtrlCheck), true);
Do you have any idea on how should I avoid the problem and execute the wanted methods before the app is closing?
Thx