What is the safest way to prevent multiple instances of a program?

I am trying to prevent my program from starting multiple instances at any given time. I read about using Windows mutexes and events, however both threads have been around for several years, and I'm curious if .net4 has a simpler and more elegant way to handle this? I thought I read about setting up a form that allowed you to discard multiple instances using a property? Can someone shed light on what is the safest and / or easiest way to prevent multiple instances of a program?

+4
source share
3 answers

The safest way is to use the built-in support in .NET, the WindowsFormsApplicationBase.IsSingleInstance property. It’s hard to guess if it’s appropriate, you didn’t put much effort into describing your exact needs. And no, nothing has changed in the last 5 years. - Hans Passant January 7 at 0:38

This was the best answer, but Hans did not present it as an answer.

+4
source

In VB, you can set this at the project level (Properties> General) for Winforms projects.

In C #, you can use code like this .. course conversion is required.

Dim tGrantedMutexOwnership As Boolean = False Dim tSingleInstanceMutex As Mutex = New Mutex(True, "MUTEX NAME HERE", tGrantedMutexOwnership) If Not tGrantedMutexOwnership Then ' ' Application is already running, so shut down this instance ' Else ' ' No other instances are running ' End If 

Oops, I forgot to mention that you will need to place GC.KeepAlive(tSingleInstanceMutex) after calling Application.Run ()

+3
source
 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Forms; namespace YourNameSpaceGoesHere { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (Process.GetProcessesByName("YourFriendlyProcessNameGoesHere").Length > 1) { MessageBox.Show(Application.ProductName + " already running!"); Application.ExitThread(); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new YourStartUpObjectFormNameGoesHere()); } } } } 
+1
source

Source: https://habr.com/ru/post/1389757/


All Articles