Single instance of an app

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'd like to prevent my app from running more than once. In VB6 this was
simple using PrevInstance. MSDN Library describes using
Diagnostics.Process.GetProcessByName to see if the the currently running
thread has another instance running. Works great as Adminstrator but throws
a SecurityPermission exception when run from a Windows account that only
belongs to BUILTIN\Users.

Is there a simple way to do this?
 
Here's what I use....

Dim m As Mutex
Dim first As Boolean
m = New Mutex(True, CN.gstrcAppTitle, first)
If Not (first) Then
'run your shutdown code here
Exit Sub
End If

HTH,
Brian
 
Brian P. Hammer said:
Here's what I use....

Dim m As Mutex
Dim first As Boolean
m = New Mutex(True, CN.gstrcAppTitle, first)
If Not (first) Then
'run your shutdown code here
Exit Sub
End If

That might fail in release mode - unless you reference the mutex later
on, it can be garbage collected after creation, allowing a second
instance to be created and think it's the first. You should either make
the mutex a static (shared) variable, or use GC.KeepAlive, or in C# my
favourite solution is:

using (Mutex m = ....)
{
// Do main application stuff here
}
 
Jon - You are correct - In my typing, I dimed instead of static declared.
Thanks for pointing it out.

Brian
 
Back
Top