To prevent my app under Window to launch twice, I stumbled upon this Mutex function.
In the App.Open method I did this among other things:
’ Windows: Mutually exclusive flag #if TargetWindows then
mutex = new NamedMutexMBS(“my app”)
if mutex.Locked then
Quit ’ already running
else
mutex.Lock
fMutex = true
end #endif
In the App.Close method I do this among other things:
#if TargetWindows then
if fMutex = true then
fMutex = false
mutex.Unlock ’ app done
else
return
end #endif
What happens ist the following:
Indeed, the second version of the app does not launch.
But when the first one is done, the second launches as if it had waited in a queue.
What’s wrong here?
// Windows: Mutually exclusive flag
#if TargetWindows then
mutex = new NamedMutexMBS(“my app”)
if mutex.Locked then
Quit // already running
else
mutex.Lock
fMutex = true
end
#endif
#if TargetWindows then
if fMutex = true then
fMutex = false
mutex.Unlock // app done
else
return
end
#endif
In the App.Opening event create and signalize entering a Mutex protected section if possible
mutexAppInUse = New Mutex("com.peterk.myapp123")
If Not mutexAppInUse.TryEnter Then // enter here if the mutex already exists
MessageBox("You cannot have more than one copy of this app running!")
Quit
End If
It’s not exactly a “memory” thing. A mutex is a shared resource that needs a specific OS call, not a memory release, to be disposed.
A explicit call at right time to release it is a good thing and design, but…
What probably happens behind the scenes is that as in Xojo, Mutex is a Xojo object, at the destruction time of that object Xojo handles the missing Leave() it in their object super destructor as we should expect.
Worth noting that mutexes don’t always get released if your app crashes. Exceptions are usually fine, but the ones where your app just disappears often leaves the mutex in place. The user may need to restart to release it.