Re: Ensure only one instance running

Mike Andrews <[email protected]> Fri, 21 Dec 2007 08:41:34 -0600
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <[email protected]>
Here's what I use.


private static Mutex _mutex;

....

string mutexName = "RUNMEONLYONCE";
try {
 _mutex = Mutex.OpenExisting(mutexName);
 _mutex.Close();
 MessageBox.Show("Only one instance of this application may be running at a
time.");
 return;
} catch (WaitHandleCannotBeOpenedException) {
 _mutex = new Mutex(false, mutexName);
}
I will prefix the name with "Local\..." from Peter's post.
I ran into that issue some time back but never was able to figure out
specifically how to prevent that from occurring.
Also, if anyone has any recommendations about this code I'm all ears.

Thanks,
Mike

On Dec 21, 2007 7:53 AM, 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.
>