Re: Ensure only one instance running

Graeme Hood <[email protected]> Fri, 21 Dec 2007 15:35:06 +0100
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <[email protected]>
Funny that VB has a specific app property for this and C# doesn't.
Thanks for the replies. 

-----Original Message-----
From: Discussion forum for developers using Windows Forms to build apps
and controls [mailto:[email protected]] On Behalf Of
Peter Ritchie
Sent: Friday, 21 December 2007 15:17
To: [email protected]
Subject: Re: [DOTNET-WINFORMS] Ensure only one instance running

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;
>

This email message is intended only for the use of the named recipient.
Information contained in this email message and its attachments may be
privileged, confidential and protected from disclosure. If you are not the
intended recipient, please do not read, copy, use or disclose this
communication to others. Also please notify the sender by replying to this
message and then delete it from your system.