DotNet · 2022年3月5日

WinForm系统退出的几种方案

几种退出运行的方法特点

关闭主窗口退出整个应用程序

    系统主窗口,实质上是Main函数中开始消息循环的窗口,这个消息循环结束后,Main函数就基本上完成了历史使命,整个应用程序自然就结束了。但事实上有时候并不是这样的,关闭窗口,只是停止了当前窗口的消息循环。对于简单应用程序来说,这种方法就足够了,但对于多线程应用程序来说,有时候不一定会达到退出目的

Application.Exit()方法

    终止所有线程上的消息循环,并关闭应用程序的所有窗口,一般情况下,无论在什么地方调用此方法,程序就能退出。但是如果你在程序中加入了某些耗时甚至是死循环的线程,那么即使是消息循环终止,程序也依然不会结束,除非能确保自已终止所有自己建的线程。
    窗体使用 form.Close()正常关闭时,通过处理 OnClosing 或 OnClosed 事件,就可以让您的应用程序清理内容、关闭文件等。如果您通过 Application.Exit 强行退出应用程序,就无法调用这些事件。

Environment.Exit(0)方法

    调用此方法,应用程序即强制退出。System.Environment.Exit(System.Environment.ExitCode);
    System.Environment.Exit(1)程序非正常运行导致退
    System.Environment.Exit(0)程序正常运行推出

End方法(VB.net)

    The End statement stops code execution abruptly, and does not invoke the Dispose or Finalize method, or any other Visual Basic code. Object references held by other programs are invalidated. If an End statement is encountered within a Try or Catch block, control does not pass to the corresponding Finally block.
    End的实现
    (1) Close all open files by the function FileSystem.CloseAllFiles in the Microsoft.VisualBasic assembly.
    (2) Call System.Environment.Exit(0) as David Anton described.
其他(不推荐作为退出程序的方法):
 System.Threading.Thread.CurrentThread.Abort();
或者 Process.GetCurrentProcess().Kill()
或者 Application.ExitThread():强制中止调用线程上的所有消息,同样面临其它线程无法正确退出的问题

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞