Mutex under Windows re-launches

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

What happens if you use TryLock here instead?

mutex = new NamedMutexMBS(“my app”)

Better use something like:

mutex = new NamedMutexMBS(“com.myappname.peter”)

here.

*and please use Code Formatting in this Forum :wink:

No need MBS for a Mutex.

Property mutexAppInUse As Mutex

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

In the App.Closing event, release the Mutex:

mutexAppInUse.Leave  // release the mutex and exit

1 Like

Thanks, guys!
Both of your solutions worked.

1 Like

The solution mark is meant to go on the post that actually answers the question. :slight_smile:

2 Likes

FWIW, I always use mutexes without releasing them when the app closes. The memory is released anyway.

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.