1

Without using a global mutex lock in an application, is there any safe way to ensure only one instance of an application is running on a system? I have found out that bugs and errors that occur during an applications lifetime in memory can lead to many problems within a system, especially if pared with a global mutex lock. Any suggestions would be much appreciated.

Thanks for reading.

someuser193
  • 55
  • 10
  • See the solution for this: https://stackoverflow.com/questions/57116228/single-instance-using-mutex-in-net – jason.kaisersmith May 27 '20 at 07:05
  • @jason.kaisersmith Thank you for your post. I looked into this solution but it appears this functionality is for VB winform applications not c# winform applications. I checked in VS and did not see that option for c# winform type applications. I appreciate your prompt response though. Any other suggestions would be much appreciated. Thanks! – someuser193 May 27 '20 at 07:21
  • Does this answer your question? [How to force C# .net app to run only one instance in Windows?](https://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows) – Sinatr May 27 '20 at 07:41
  • 1
    There is [an answer](https://stackoverflow.com/a/6416663/1997232) which enumerate processes to check if one is already running. Other idea is to create file with exclusive access if you dislike mutexes. But in general mutex with `try/finally` (like in [this answer](https://stackoverflow.com/a/184143/1997232), where `using` ensures freeing mutex) is good enough. – Sinatr May 27 '20 at 07:44
  • I am not exactly opposed to using a mutex lock but I worry that if exceptions or errors occur during my apps lifetime while in memory and the app cannot recover from these errors, a mutex lock might make the app unresponsive and/or error prone thus leaving the system in a bad state such as a undefined state. Would a try catch finally block be an ideal thing for a mutex lock on an app? To give you more details the app is multi threaded with system timers. Thanks for the inputs! – someuser193 May 27 '20 at 08:04
  • Everyone who posted, thanks for reading thist and taking the time to answer this. The help is much appreciated! – someuser193 May 28 '20 at 01:46

1 Answers1

4

You can use Mutex to ensure a single instance app. Put the following code in the Main function of your WinForms app:

static class Program
{
    static Mutex mutex = new Mutex(true, "<some_guid_or_unique_name>");

    [STAThread]
    static void Main()
    {
        if (mutex.WaitOne(TimeSpan.Zero, true))
        {
           // do the app code
           Application.Run();

           // release mutex after the form is closed.
           mutex.ReleaseMutex();
           mutex.Dispose();
        }
    }
}
JeremyRock
  • 396
  • 1
  • 8
  • JeremyRock, Thanks for your time and suggestions! I have looked into this and I will try it. Thanks for reading the post! – someuser193 May 28 '20 at 01:45