0

Im currently trying to create a "watchdog" in c# which checks if a mutex is in use, if it is everything is good, if not --> start the application.

Works fine for the first time, but as soon as the main application stops / ends, it wont recognize that. It still thinks that the mutex is in use and also seems to lock it to the watchdog process?

        string mutexdog = "dog";
        try
        {
            Mutex.OpenExisting(mutexdog);
            System.Environment.Exit(0);
        }
        catch
        {
            Program._m = new Mutex(true, mutexdog);
        }
        while(true)
        {
            string mutexmain = "main";
            try
            {
                Mutex.OpenExisting(mutexmain);

                Console.WriteLine("Main is running");
            }
            catch
            {
                Console.WriteLine("Main is not running, starting!");
                Process p = new Process();
                p.StartInfo.FileName = "main.exe";
                p.Start();
                Thread.Sleep(1500);
            }
            Thread.Sleep(500);
        }

Is there any way to check if a mutex is being used without locking it up? I would prefer to do it over a mutex due to multiple reason and other issues i had previously by checking for a process name...

Dennis
  • 127
  • 10
  • 1
    Why do you want this? Such mechanisms are already available, eg services can be restarted N times after a failure. If you want an application that's always running, you should create a service and set its retry properties – Panagiotis Kanavos Dec 19 '18 at 15:39
  • Thanks for the reply, but i dont want to use a service and also would love to know a solution to do it over the "mutex way" and don ditch it when i run into an issue :) – Dennis Dec 19 '18 at 15:43
  • You assume there is such a way. For an exception to reach that point it means that either the code is badly written and leaks exceptions (fix it), or b) it's one of the uncatchable exceptions and the application is dead by that point. Manually starting a process doesn't give you *any* guarantee it will run or that the resources captured by the previous instance will be free. That's why services include a delay before restarting. – Panagiotis Kanavos Dec 19 '18 at 15:45
  • Possible duplicate of [How to find that Mutex in C# is acquired?](https://stackoverflow.com/questions/3013212/how-to-find-that-mutex-in-c-sharp-is-acquired) – Sinatr Dec 19 '18 at 15:47

0 Answers0