static void Main() {
Application.EnableVisualStyles();
Application.Run(new MainForm());
// 程式正常結束前,強制殺掉殘留進程
string exe = Process.GetCurrentProcess().MainModule.FileName;
string exeName = System.IO.Path.GetFileName(exe);
RunCmd($"taskkill /im \"{exeName}\" /f");
}
static string RunCmd(string cmd) {
using (var p = new Process()) {
p.StartInfo = new ProcessStartInfo("cmd.exe", "/c " + cmd) {
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
p.Start();
return p.StandardOutput.ReadToEnd();
}
}
// 在任意位置立即終結自身
Process.GetCurrentProcess().Kill();
// 注意:不會執行 finally、Dispose、Finalizer,資源可能洩漏
// WinForms
Application.Exit(); // 觸發 FormClosing/FormClosed,釋放資源
// WPF
Application.Current.Shutdown();
// 主控台
Environment.Exit(0); // 執行 finally、Finalizer
| 方法 | 執行 Finally | 適用場景 | 風險 |
|---|---|---|---|
| Application.Exit() | 是 | 正常 UI 關閉 | 若訊息迴圈卡住無效 |
| Process.Kill() | 否 | 緊急終止、除錯 | 資料遺失、檔案損毀 |
| taskkill /f | 否 | 外部腳本、安裝程式清理 | 同 Kill,且需啟動 cmd |
優先使用框架提供的正常關閉流程;只有在程式無回應、必須強制釋放資源時,才考慮 Kill() 或 taskkill。