Closing function in a VB.NET console application

筅森魡賤 提交于 2019-12-02 04:26:52

问题


How can I fire off a function when it detects the console closing when using Environment.Exit(0)?


回答1:


The simplest way of doing this is probably to handle the AppDomain.ProcessExit event, which is raised when the application's parent process exits.

For example:

Module MyApp

    Sub Main()
        ' Attach the event handler method
        AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf MyApp_ProcessExit

        ' Do something
        ' ...

        Environment.Exit(0)
    End Sub

    Private Sub MyApp_ProcessExit(sender As Object, e As EventArgs)
        Console.WriteLine("App Is Exiting...")
    End Sub

End Module

But calling Environment.Exit may not be the best solution to your original problem. In general, the only time it is necessary to use this method is when there might be other foreground threads running. And in that case, it's worth investigating ways of gracefully terminating those other threads without resorting to draconian measures that kill the entire process.

Environment.Exit, despite the somewhat pleasant-sounding name, is a pretty brutal measure. It's not quite as bad as clicking "End Task" in the Windows Task Manager (and note that if you do that, the ProcessExit event will not be raised, meaning that the above suggestion will not work), but it's probably not the solution you really want, either.



来源:https://stackoverflow.com/questions/10099377/closing-function-in-a-vb-net-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!