Posts Tagged ‘mutex’

Mutex – single instance of program – VB – Winforms

February 19, 2015

Three ways to use mutexes to guarantee that your VB.Net winforms application only runs one instance at a time on a given host.
I don’t know why I redid this three times yesterday – I must have made some mistake that led me to believe that the first two tries weren’t working!


Public Class globals

Public Shared unique_mutex As Mutex

'ref: http://odetocode.com/blogs/scott/archive/2004/08/20/the-misunderstood-mutex.aspx
' http://renren.io/questions/35665/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows
' flavor: TryOpenExisting
Public Shared Function guarantee_unique_instance_of_program() As String
Dim sMutexName As String = "Global\VcProcessPaymentsMutex"
Dim bAlreadyExisting As Boolean = False
Dim bFirstTimeCreated As Boolean = False

' http://renren.io/questions/5447537/c-sharp-mutex-issue-to-prevent-second-instance

bAlreadyExisting = Mutex.TryOpenExisting(sMutexName, globals.unique_mutex)

Select Case bAlreadyExisting
Case True
Return "FAILURE Instance already running"
Case False
globals.unique_mutex = New Mutex(False, sMutexName, bFirstTimeCreated)
Return "SUCCESS"
End Select

End Function

'ref: http://odetocode.com/blogs/scott/archive/2004/08/20/the-misunderstood-mutex.aspx
' http://renren.io/questions/35665/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows
' I think this is the ScottGu method (more or less)
Public Shared Function guarantee_unique_instance_of_program_GOOD3() As String
Dim bFirstTimeCreated As Boolean = False
globals.unique_mutex = New Mutex(False, "Global\VcProcessPaymentsMutex")
If (Not unique_mutex.WaitOne(0, False)) Then
Return "FAILURE Instance already running"
Else
Return "SUCCESS"
End If
GC.Collect()
End Function

Public Shared Sub release_mutex()
unique_mutex.ReleaseMutex()
End Sub

' this is the "FirstTimeCreated" flavor
' ALSO GOOD (why did I redo this yesterday?)
' flavor: TryOpenExisting
_
Public Shared Function guarantee_unique_instance_of_program_GOOD2() As String

'1) try to open one that is existing
Dim bTryToOpenExisting As Boolean = False
bTryToOpenExisting = Mutex.TryOpenExisting("Global\VcProcessPaymentsMutex", unique_mutex)
If (bTryToOpenExisting) Then
Return "FAILURE Instance already running"
End If

' 2) if it didn't exist yet, then create it
Dim bFirstTimeCreated As Boolean = False
Using unique_mutex As New Mutex(False, "Global\VcProcessPaymentsMutex", bFirstTimeCreated)

If (Not bFirstTimeCreated) Then ' this should never be hit
Return "FAILURE Instance already running"
End If

GC.Collect()
End Using

Return "SUCCESS"

End Function


(more…)

Advertisements