Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to prevent my program from running multiple instances at any given time. I have read about using mutex and windows events, however both threads were several years old, and I'm curious if with .net4 there is a more simple, and more elegant way to deal with this? I thought I had read about a setting for the form that allowed you to deny multiple instances by the property? Could someone shed some light on what the safest and/or simplest way to prevent multiple instances of a program is?

like image 258
Fuzz Evans Avatar asked Feb 21 '23 22:02

Fuzz Evans


2 Answers

The safest way is to use the built-in support in .NET, WindowsFormsApplicationBase.IsSingleInstance property. Hard to guess if it is appropriate, you didn't make much effort describing your exact needs. And no, nothing changed in the past 5 years. – Hans Passant Jan 7 at 0:38

This was the best answer but Hans didn't submit it as an answer.

like image 67
Fuzz Evans Avatar answered Feb 25 '23 01:02

Fuzz Evans


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

In C# you can use code similar to this.. needs conversion of course..

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

Whoops, I forgot to mention that you will need to place GC.KeepAlive(tSingleInstanceMutex) after your Application.Run() call

like image 30
Sam Axe Avatar answered Feb 25 '23 01:02

Sam Axe