Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting and restarting my crashed .NET application

Tags:

.net

How can I detect that my .NET application has crashed, and then restart it?

like image 568
Hosam Aly Avatar asked Feb 08 '09 14:02

Hosam Aly


3 Answers

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.

like image 179
Hosam Aly Avatar answered Nov 08 '22 00:11

Hosam Aly


If this is a Windows Forms app:

  • Set jitDebugging = true in App.Config. This prevents the built-in Windows Forms unhandled exception handler being triggered.

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 it's a Windows Forms app, call the Application.Restart method in your CatchFatalException event handler.
  • Otherwise you will instead need to p/invoke to the application restart and recovery native functions. That link discusses Vista, but in my tests it works just fine on XP as well.
like image 37
HTTP 410 Avatar answered Nov 08 '22 02:11

HTTP 410


  • run the work inside an AppDomain; use the primary AppDomain to monitor it (doesn't guard against process kill, though)
  • lots of exception handling! i.e. don't let a fatal error tear down the process
  • run it in something that already has recycling built in - IIS for example
like image 44
Marc Gravell Avatar answered Nov 08 '22 02:11

Marc Gravell