如何检测我的.NET应用程序是否崩溃,并重新启动它?
如何检测我的.NET应用程序是否崩溃,并重新启动它?
另一个解决方案(基于 这个例子),是创建一个控制应用程序的启动器:
class LauncherProgram
{
static int count = 3;
static void Main()
{
Launch();
Thread.Sleep(Timeout.Infinite);
}
static void Launch()
{
Process process = new Process();
process.StartInfo.FileName = "MyApp.exe";
process.EnableRaisingEvents = true;
process.Exited += LaunchIfCrashed;
}
static void LaunchIfCrashed(object o, EventArgs e)
{
Process process = (Process) o;
if (process.ExitCode != 0)
{
if (count-- > 0) // restart at max count times
Launch();
else
Environment.Exit(process.ExitCode);
}
else
{
Environment.Exit(0);
}
}
class ProcessMonitorProgram
{
const string myProcess = "MyApp.exe";
static void Main()
{
new Timer(CheckProcess, null, 0, 60 * 1000);
Thread.Sleep(Timeout.Infinite);
}
static void CheckProcess(object obj)
{
if (Process.GetProcessesByName(myProcess).Length == 0)
Process.Start(myProcess);
}
}
这个解决方案的一个问题是它会一直让进程重启,直到监控应用程序本身被终止。