Using code to hook the console close event from this thread, I sometimes get a NullReferenceException with no stacktrace (most of the times I don\'t). It happen
For the vb.net bods who are struggling with this, my code is ...
'declaration
Private Declare Function SetConsoleCtrlHandler Lib "kernel32" (ByVal handlerRoutine As ConsoleEventDelegate, ByVal add As Boolean) As Boolean
Public Delegate Function ConsoleEventDelegate(ByVal [event] As ConsoleEvent) As Boolean
'The close function...
Public Function Application_ConsoleEvent(ByVal [event] As ConsoleEvent) As Boolean
Console.WriteLine("We're closing it all down: ")
Return False
End Function
'creating the handler.
If Not SetConsoleCtrlHandler(New ConsoleEventDelegate(AddressOf Application_ConsoleEvent), True) Then
Console.WriteLine("Unable to install console event handler.")
Exit Sub
End If
The most typical issue with code like that is not keeping a reference to the delegate instance. The one you pass as the first argument to SetConsoleCtrlHandler(). The garbage collector cannot see references held to a delegate object by unmanaged code. So this will, eventually, bomb when the garbage collector runs:
SetConsoleCtrlHandler(Handler, true);
which is the exact same thing as
SetConsoleCtrlHandler(new EventHandler(Handler), true);
assuming you used the types in the linked code. The author of that code carefully avoided this issue by making _handler a static variable. As opposed to the temporary delegate instance that is created by the previous two lines of code. Storing it in a static variable ensures it stays referenced for the life of the program. The Right Thing to do in this particular case since you are actually interested in the events until the program ends.