Is using a Mutex to prevent multiple instances of the same program from running safe?

It is more usual and convenient to use Windows events for this purpose. E.g.

static EventWaitHandle s_event ;

bool created ;
s_event = new EventWaitHandle (false, 
    EventResetMode.ManualReset, "my program#startup", out created) ;
if (created) Launch () ;
else         Exit   () ;

When your process exits or terminates, Windows will close the event for you, and destroy it if no open handles remain.

Added: to manage sessions, use Local\ and Global\ prefixes for the event (or mutex) name. If your application is per-user, just append a suitably mangled logged-on user’s name to the event name.

Leave a Comment