我在应用程序的启动形式的 .load even 处理程序中有以下循环:
While (Not Directory.Exists(My.Settings.pathToHome))
Dim response As MessageBoxResult = Forms.MessageBox.Show("Some message","Some Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
If response = MessageBoxResult.Cancel Then
Me.Close() 'can comment this line or next or leave both uncommented
Forms.Application.Exit()
End If
options.ShowDialog() 'this line can be commented
End While
如果用户在消息框中选择"取消",则可以执行 Me.Close() 和 Forms.Application.Exit() 行,但不是应用程序终止,而是 while 循环无限。 这可以通过单步执行调试器来显式看到。
选项窗体和消息框在消息框上第一次取消后永远不会打开,尽管可能会在循环旋转时看到其中一个或两个"闪烁"。 如果单步执行调试器,我会听到消息框中的"提示音",尽管它没有出现。
我想我也可以在那里添加一个"退出子"。 但这是否有必要,是否可靠? 这似乎很奇怪,尤其是 application.exit 没有成功终止线程。
在Forms.Application.Exit
之后Exit While
。
Application.Exit
仍然允许线程完成它们正在做的事情,并且由于您实际上处于无限循环中,因此它永远不会真正让应用程序关闭。
Application.Exit()
只是告诉Windows你的应用程序想要退出,并清理一些资源。它不会停止您的代码,因此您的循环会继续运行。
您负责让所有线程停止。您确实可以通过添加 Exit Sub
.或者一些Environment
方法,如Environment.Exit()
或Environment.FailFast()
,但两者都是矫枉过正的,你只会使用它们来隐藏糟糕的设计。只需退出循环即可。
你只需要打破循环。正如其他答案已经全面涵盖的那样,Application.Exit() 会发出关闭应用程序的信号,但它允许所有应用程序线程完成它们正在做的事情,因此当您留在该循环中时,您的主线程将永远不会完成。
打破这个循环的几种方法;最合适的方法是退出 while 语句,或者退出整个函数。
While (Not Directory.Exists(My.Settings.pathToHome))
Dim response As MessageBoxResult = Forms.MessageBox.Show("Some message","Some Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
If response = MessageBoxResult.Cancel Then
Me.Close() 'can comment this line or next or leave both uncommented
Forms.Application.Exit()
Exit While 'or Exit Sub
End If
options.ShowDialog() 'this line can be commented
End While