Preventing Multiple Instances of An Application

Have you experienced a user that run an EDI application two times in one computer, which cause the data that being transferred became haywire? I have.

One way to solve this problem is by preventing the second instance of the application to run.

In Visual Basic 6 we can use the code below:

    Dim rc As Long

    If App.PrevInstance Then
        rc = MsgBox("Application is already running", vbCritical, App.Title)
        Exit Sub
    Else
        frmMain.Show
    End If

In Visual Basic .NET (2005) we can use the code below:

    Dim oMutex As System.Threading.Mutex
    oMutex = New System.Threading.Mutex(False, "ca91daff-26a3-49cd-97e0-4d57b50c9d3b")
    If (oMutex.WaitOne(0, False) = False) Then
        MessageBox.Show("The Accpac Interface is already running")
        Exit Sub
    End If

The “ca91daff-26a3-49cd-97e0-4d57b50c9d3b” is the application GUID. You can find it in the Project Properties -> Assembly Information

ProjectProperties

AssemblyInformation

Another way of doing it is by using “Make single instance application” option in the Project Properties, I have never used this method though.

MakeSingleInstanceApplication

One more way to prevent multiple instance is by checking all of active processes, see the code below:

    Dim instanceCount As Integer = Process.GetProcessesByName("explorer").Count()
    Console.WriteLine(String.Format("{0} Instances Running", instanceCount.ToString()))
    Console.ReadLine()

References: