all groups > dotnet clr > november 2004 >
You're in the

dotnet clr

group:

AppDomain.CurrentDomain.ProcessExit && CTRL-C


AppDomain.CurrentDomain.ProcessExit && CTRL-C Stephen Gennard
11/29/2004 11:33:47 AM
dotnet clr:
Hi,



My console application needs to do some shutdown processing even when a
CTRL-C is pressed. So I installed ProcessExit event handler and was
surprised to find this did not get invoked when a CTRL-C occurs.



I then set about using the Win32 API to install a console ctrl handler to do
the work for me. In the process of doing this my ProcessExit event started
to work! (see example below).



Is this expected behavior or is it a clr bug?



(Using Microsoft (R) .NET Framework version 1.1.4322)



--
Stephen

--Demo:

using System;
using System.Runtime.InteropServices;

public class BreakHandlerBugDemo
{
public static int Main(String[] args)
{
AppDomain.CurrentDomain.ProcessExit += new
EventHandler(currentDomain_ProcessExit);

Console.Write("Do you want to install a Win32 console ctrl handler? ");
string dowork = Console.In.ReadLine();
if (dowork.Length >= 1 && (dowork[0] == 'y' || dowork[0] == 'Y'))
{
NativeWindowsBreakHandler.RegisterBreakHandler();
Console.WriteLine("-- installed");
}
else
{
Console.WriteLine("** no console ctrl handler installed");
}
Console.WriteLine();

Console.Write("Press CTRL-C now! (you should see PASS...)");
Console.In.ReadLine();
return 0;
}

private static void currentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("\nPASS: ProcessExit event called!");
}

}

internal class NativeWindowsBreakHandler
{

// Declare the SetConsoleCtrlHandler function as external and receiving a
delegate.
[DllImport("Kernel32")]
private static extern Boolean SetConsoleCtrlHandler(HandlerRoutine Handler,
Boolean Add);

// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
private delegate Boolean HandlerRoutine(CtrlTypes CtrlType);

// An enumerated type for the control messages
// sent to the handler routine.
private enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}

static internal void RegisterBreakHandler()
{
HandlerRoutine hr = new HandlerRoutine(Handler);
SetConsoleCtrlHandler(hr, true);
}

// A private static handler function in the MyApp class.
static Boolean Handler(CtrlTypes CtrlType)
{
// A switch to handle the event type.
switch(CtrlType)
{
case CtrlTypes.CTRL_C_EVENT :
case CtrlTypes.CTRL_BREAK_EVENT :
return true;
}
return false;
}
}

RE: AppDomain.CurrentDomain.ProcessExit && CTRL-C kitg NO[at]SPAM ONLINE NO[at]SPAM microsoft.com
11/30/2004 9:36:01 PM
Stephen, it's odd, but expected. The good news is, if you move to V2.0,
We've got a handler on Console now, to catch Ctrl-C, so we can deal with
this for you.
Re: AppDomain.CurrentDomain.ProcessExit && CTRL-C Stephen Gennard
11/30/2004 10:24:03 PM
Thanks kit. That is good news.

[quoted text, click to view]

AddThis Social Bookmark Button