Re: Ensure only one instance running

Peter Ritchie <[email protected]> Fri, 21 Dec 2007 09:16:45 -0500
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <LISTSERV%[email protected]>
The semantics are correct, but there's some other things to consider:

I would suggest that you make mutex a static member to avoid it getting
collected prematurely.  i.e. mutex is technically available for collection
after initialization and before the "if (!firstInstance)"...

Also, unless you prepend @"Local\" to the start of your mutex name, you'll
have a single application per computer, not per desktop.  On terminal
services (like remote desktop and fast user switching) this mutex could be
shared between sessions meaning if one user has the application running in
their session, a user in another session would not be able to run the
application.

On Fri, 21 Dec 2007 14:53:16 +0100, Graeme Hood <[email protected]> wrote:

>I have this code to make sure my app can't run twice. But I seem to
>remember there was a newer/better way in the latest .Net FW.
>
>Is there?
>
>====================================================
>
>public static void Main()
>
>bool firstInstance = false;
>
>string safeName = Application.UserAppDataPath.Replace(@"\", "_");
>
>Mutex mutex = new Mutex(true, safeName, out firstInstance);
>
>if (!firstInstance) return;
>