【问题标题】:Closing function in a VB.NET console applicationVB.NET 控制台应用程序中的关闭函数
【发布时间】:2012-04-23 08:53:51
【问题描述】:

当使用Environment.Exit(0) 时检测到控制台关闭时,我如何触发函数?

【问题讨论】:

    标签: .net vb.net console-application exit exit-code


    【解决方案1】:

    执行此操作的最简单方法可能是处理AppDomain.ProcessExit event,它在应用程序的父进程退出时引发。

    例如:

    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
    

    但是致电Environment.Exit 可能不是解决您最初问题的最佳方法。一般来说,the only time it is necessary to use this method is when there might be other foreground threads running。在这种情况下,值得研究如何优雅地终止那些其他线程,而无需采取会杀死整个进程的严厉措施。

    Environment.Exit,尽管这个名字听起来有点悦耳,但却是一个相当残酷的措施。它还没有在 Windows 任务管理器中单击“结束任务”那么糟糕(请注意,如果您这样做,则不会引发 ProcessExit 事件,这意味着上述建议将不起作用),但这也可能不是您真正想要的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多