How can I detect that my .NET application has crashed, and then restart it?
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With