Reputation: 42443
How can I detect that my .NET application has crashed, and then restart it?
Upvotes: 11
Views: 6357
Reputation: 42443
Another solution (based on this example) is to create a launcher that controls the application:
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;
process.Start();
}
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);
}
}
Upvotes: 15
Reputation: 17608
If this is a Windows Forms app:
Now regardless of whether this is a Windows Forms app or a console app:
Register for the Application.ThreadException event, e.g. in C#:
Application.ThreadException += new Threading.ThreadExceptionHandler(CatchFatalException);
At this point, your app is already on its way into a black hole. What happens next depends on whether or not this is a Windows Forms app:
Upvotes: 8
Reputation: 1062600
Upvotes: 5
Reputation: 42443
A possible solution is to create another process to monitor your application, and restart it if it is terminated:
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);
}
}
One of the problems with this solution is that it will keep the process restarting forever, until this monitoring application itself is terminated.
Upvotes: 1