tags:

views:

1598

answers:

5

In order to allow only a single instance of an application running I'm using mutex. The code is given below. Is this the right way to do it? Are there any flaws in the code?

How to show the already running application when user tries to open the application the second time. At present (in the code below), I'm just displaying a message that another instance is already running.

    static void Main(string[] args)
    {
        Mutex _mut = null;

        try
        {
            _mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName);
        }
        catch
        {
             //handler to be written
        }

        if (_mut == null)
        {
            _mut = new Mutex(false, AppDomain.CurrentDomain.FriendlyName);
        }
        else
        {
            _mut.Close();
            MessageBox.Show("Instance already running");

        }            
    }
+1  A: 

Have a look at this question

There is a link to this article: the misunderstood mutex where the usage of a mutex is explained.

tanascius
+3  A: 

I did it this way once, I hope it helps:

bool createdNew;

Mutex m = new Mutex(true, "myApp", out createdNew);

if (!createdNew)
{
    // myApp is already running...
    MessageBox.Show("myApp is already running!", "Multiple Instances");
    return;
}
Peter D
This code is not safe or correct: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567
Sam Saffron
A: 

Check out the code sample shown on this page

In short, you use the overload Mutex ctor(bool, string, out bool) which tells you via an out parameter, whether you got ownership of the Named Mutex. If you're the first instance, this out param would contain true after the ctor is called - in which case you proceed as usual. If this param is false, it means another instance has already got ownership/is running, in which case you show an error message "Another instance is already running." and then exit gracefully.

Gishu
+2  A: 
static void Main() 
{
  using(Mutex mutex = new Mutex(false, @"Global\" + appGuid))
  {
    if(!mutex.WaitOne(0, false))
    {
       MessageBox.Show("Instance already running");
       return;
    }

    GC.Collect();                
    Application.Run(new Form1());
  }
}

Source : http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx

Milen
This code is not safe or correct... http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567
Sam Saffron