.NET application crashes when capturing console close event only in Release build

1

I have a .NET application (.NET Framework 4) which monitors certain machines. I am capturing the console close event (actually CTRL+C) and ask the user if he/she is sure about it. In case the answer is yes, the application proceeds to run a method that closes open resources. When running it in the Debug build it works fine, the problem is running it in Release mode, when CTRL+C is pressed, the application crashes and this event is shown in Window's Event Viewer.

 <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
 <System>
  <Provider Name=".NET Runtime" /> 
  <EventID Qualifiers="0">1026</EventID> 
  <Level>2</Level> 
  <Task>0</Task> 
  <Keywords>0x80000000000000</Keywords> 
  <TimeCreated SystemTime="2018-11-08T13:39:31.140511100Z" /> 
  <EventRecordID>25125</EventRecordID> 
  <Channel>Application</Channel> 
  <Computer>this.computer</Computer> 
  <Security /> 
  </System>
 <EventData>
  <Data>Aplicación: FooBar.exe Versión de Framework: v4.0.30319 Descripción: el proceso terminó debido a una excepción no controlada. Información de la excepción: código de la excepción c0000005, dirección de la excepción 0000000000E80B18</Data> 
  </EventData>
  </Event>

Below I add the code I use to invoke the method that cleans resources.

enum CtrlType
{
    CTRL_C_EVENT = 0,
    CTRL_BREAK_EVENT = 1,
    CTRL_CLOSE_EVENT = 2,
    CTRL_LOGOFF_EVENT = 5,
    CTRL_SHUTDOWN_EVENT = 6
}

private delegate bool EventHandler(CtrlType sig);

[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private static bool Handler(CtrlType sig)
{
    if (sig == CtrlType.CTRL_C_EVENT)
    {
        DialogResult dr = MessageBox.Show("Seguro que quieres cerrar la aplicación?", "Confirmación de cierre", MessageBoxButtons.YesNo);
        switch (dr)
        {
            case DialogResult.Yes:
                Environment.Exit(0); // se ejecutará la limpieza y luego se cerrará la aplicacion
                return false;
            case DialogResult.No:
                return true;
            default:
                break;
        }
    } else
    {
        DialogResult exitDialog = MessageBox.Show("La aplicación procederá a cerrarse", "Cerrando Supervisor", MessageBoxButtons.OK);
    }
    return true;
}
[DllImport("user32.dll")]
public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);

[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
#endregion

#region Methods
public static void Main(string[] args)
{
    SetConsoleCtrlHandler(Handler, true);
    Console.Title = GlobalConfig.Title;
    Console.Clear();
    DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), 0xF060, 0x00000000);
    ShowWindow(GetConsoleWindow(), 5);

    //AppDomain.CurrentDomain.ProcessExit += new System.EventHandler(CleanBeforeExit);

    init();
}

static void CleanBeforeExit(object sender, EventArgs e) { ... }

If I use the ProcessExit way it won't crash, but it won't execute my CleanBeforeExit method either.

Does anybody know how to solve this? I don't think the client (a really important one) would accept an application in Build config (or isn't it really important?).

c#
.net
events
crash
event-handling

1 Answer

0

I ended up solving it by using an EventHandler variable

static EventHandler _handler;

and

_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);

instead of

SetConsoleCtrlHandler(Handler, true);
answered on Stack Overflow Nov 13, 2018 by Sergi Mascaró

User contributions licensed under CC BY-SA 3.0