How to Close Console Application Gracefully on Windows Shutdown

后端 未结 3 919
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 22:50

I am trying to close my vb.net console app gracefully when windows shutdown occurs. I have found examples that call the Win32 function SetConsoleCtrlHandler that all basically

3条回答
  •  醉话见心
    2021-01-20 23:32

    Pointers to functions are represented in .Net as delegates. A delegate is a kind of object and, like any other object, if there are no references to it then it will be garbage collected.

    The expression (AddressOf Application_ConsoleEvent) creates the delegate. SetConsoleCtrlHandler is a native function, so it doesn't understand delegates; it receives a raw function pointer. So the sequence of operations is:

    1. (AddressOf Application_ConsoleEvent) creates the delegate.
    2. SetConsoleCtrlHandler receives a raw function pointer that points to the delegate, and stores the raw pointer for later use.
    3. Time passes. Note that nothing is referencing the delegate now.
    4. Garbage collection occurs and the delegate is collected because it is unreferenced.
    5. The application is closing, so Windows tries to notify you by calling the raw function pointer. This points to a non-existent delegate so you crash.

    You need to declare a variable to keep a reference to the delegate. My VB is very rusty, but something like:

    Shared keepAlive As ConsoleEventDelegate
    

    Then

    keepAlive = AddressOf ConsoleEventDelegate
    If Not SetConsoleCtrlHandler(keepAlive, True) Then
        'etc.
    

提交回复
热议问题