Difference between revisions of "Mutex"

From Xojo Documentation

(Clarified that Mutex is shared per user account (not system-wide).)
Line 39: Line 39:
If Not mMutex.TryEnter Then
If Not mMutex.TryEnter Then
   MsgBox("You cannot have more than one copy of this app running!")
   MessageBox("You cannot have more than one copy of this app running!")
   mMutex = Nil
   mMutex = Nil

Latest revision as of 22:48, 28 August 2019

Class (inherits from CriticalSection)

A type of CriticalSection that has operating system-wide scope and is visible to other applications.


Constructor(name as String)

Enter TryEnter


Mutex is short for Mutual Exclusion object. It allows several applications to share the same system resource, but not simultaneously. The suggested usage of a Mutex is to create a Mutex with a unique name when the application launches. When the application needs to use the resource, it calls the Enter or TryEnter methods to get a "lock" on the resource and calls the Leave method when it is finished (to release the lock). When you have a lock on a resource, it means you are allowed to use it.

The most common use of a Mutex is to determine whether another instance of your application is currently running in the same user account (not system-wide). You create a named Mutex in the application's open event and then check to see if you can get a lock on it. If the lock fails, then you know there's another instance of your application running. You can also use Mutexes to work with resources that are shared between applications in the same user account (not system-wide) such as a serial port, printer, or some other system device.

You can call Enter or TryEnter multiple times in the same way as with a CriticalSection, including recursive calls.

For web applications, the name value must not be the same as your Application Identifier.

If a thread that has a lock crashes, the lock is not released.

If you use an IPCSocket that uses SpecialFolder.Temporary to create the IPCSocket file, then the name of the file cannot be the same name as a Mutex (as it also uses that folder).

Sample Code

Add a property to your app:

mMutex As Mutex

In App.Open event handler, you can attempt to create a Mutex.

mMutex = New Mutex("MutexExample")

If Not mMutex.TryEnter Then
MessageBox("You cannot have more than one copy of this app running!")
mMutex = Nil
End If

In App.Close, you can release the Mutex:

If mMutex <> Nil Then
End If

See Also

Application, CriticalSection, Semaphore, Thread classes.