You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现应用程序退出时自动重启?现有代码运行报错求助

How to Make a Console App Restart Automatically on Exit (Fixing Your "dotnet has stopped working" Error)

Hey there! Let's work through this together—since you're new to programming, I'll break everything down clearly so you understand what's going on, not just copy-paste code.

First, Why Your Current Code Is Causing the Error

Your code uses AppDomain.CurrentDomain.ProcessExit, which triggers as the process is already shutting down. At this point, .NET is cleaning up resources, closing system handles, and preparing the process to terminate. Trying to launch a new process from inside this event clashes with the system's shutdown logic—that's exactly why you're seeing the "dotnet has stopped working" error.

Also, hardcoding @"MyApp.exe" is risky: if you run the app via dotnet run or the executable lives in a different folder, this path won't point to the correct file.

Let's Fix This: Two Reliable Approaches

Approach 1: Use a Main Loop (Simplest for Beginners)

Instead of relying on exit events, structure your app to run in a straightforward flow. When the user exits the current session, we'll start a new instance first, then close the current one. This avoids shutdown-time conflicts entirely.

Here's the code:

using System;
using System.Diagnostics;

namespace AutoRestartApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello from the app! Press Enter to exit and restart...");
            Console.ReadLine();

            // Get the full path of the current executable (no hardcoding!)
            string currentExePath = Process.GetCurrentProcess().MainModule.FileName;
            
            // Launch a fresh instance of the app
            Process.Start(currentExePath);
            
            // Cleanly exit the current instance
            Environment.Exit(0);
        }
    }
}

Approach 2: Handle Exit Events Safely (For More Control)

If you need to handle different exit scenarios (like Ctrl+C or unhandled errors), use Console.CancelKeyPress to catch user-initiated shutdowns, and trigger a restart before the process begins shutting down.

using System;
using System.Diagnostics;

namespace AutoRestartApp
{
    class Program
    {
        private static bool _shouldRestart = true;

        static void Main(string[] args)
        {
            // Handle Ctrl+C presses
            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true; // Stop the immediate shutdown
                _shouldRestart = true;
                Console.WriteLine("\nRestarting...");
                RestartApp();
            };

            Console.WriteLine("App running! Press Enter to restart, or Ctrl+C...");
            Console.ReadLine();

            if (_shouldRestart)
            {
                RestartApp();
            }
        }

        private static void RestartApp()
        {
            string currentExePath = Process.GetCurrentProcess().MainModule.FileName;
            Process.Start(currentExePath);
            Environment.Exit(0); // Exit right after launching the new process
        }
    }
}

Clearing Up the Concepts You Were Confused About

What Is AppDomain?

An AppDomain is a .NET-specific sandbox within a single process—think of it as a container for running code that can be loaded/unloaded independently. The ProcessExit event fires when the entire process is about to exit, but as we saw, this is too late to safely start a new process without causing conflicts.

Why Application.Exit Didn't Make Sense

Application.Exit() is a method for Windows Forms GUI apps, not console apps. It tells the WinForms message loop to stop, closing all windows and exiting the app. Since you're building a console app, this method doesn't apply to your scenario—that's why the MSDN examples felt irrelevant!

Key Tips to Avoid Future Issues

  • Always get the current executable path dynamically with Process.GetCurrentProcess().MainModule.FileName instead of hardcoding it. This works whether you're running via dotnet run, a published executable, or from any folder.
  • Use Environment.Exit(0) to exit the current process cleanly after starting the new one—this ensures the old process doesn't hang around unexpectedly.

内容的提问来源于stack exchange,提问作者Alex V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:27:53