Search code examples
c#process-management

Management running process


I have a console application that runs on my computer. When the application throws an exception, I want to restart the application. How can I accomplish this?


Solution

  • You can instantiate a Timer that check every n seconds if the process is alive, for example you can write i function like the following to verify if the process is alive :

     public static bool ProcessExist(string processname)
            {
                Process[] aProc = Process.GetProcessesByName(processname);
                return (aProc.Length > 0);
            }
    

    Every Tick of the timer you can check if the process is alive or not, if not you can relaunch it.

    Another method could be use a ManagementEventWatcher for get fired an event every time that a process stop on your machine, so for example :

    ManagementEventWatcher stopWatchProcess = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
                    stopWatchProcess.EventArrived += new EventArrivedEventHandler(stopWatchProcess_EventArrived);
                    stopWatchProcess.Start();
    
    
    private void stopWatchProcess_EventArrived(object sender, EventArrivedEventArgs e) {
                string processName = (string)e.NewEvent.Properties["ProcessName"].Value;
                if(processName == "yourprocess.exe") {
                  //Do Something
         }
            }