1

I have an application, "myprogram.exe", which calls functions and code inside a dll, one of this functions that "myprogram.exe" calls create a new instance of a winform, "MyForm.cs" and then show it using form.show();.

I can have 'n' number of "myprogram.exe" instances running, but I want to have only one instance of "MyForm.cs" for each instance of "myprogram.exe".

The problem that I have is that even thought I'm using mutex inside "MyForm.cs" to create a mutex and them ask if an instance of it is already running, sometimes, it creates another instance, despite the mutex.

Is there another way that I can use to validate if an instance of "myprogram.exe" has already created an instance of "MyForm.cs".

Vic
  • 2,878
  • 4
  • 36
  • 55
  • See http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 and http://stackoverflow.com/questions/819773/run-single-instance-of-an-application-using-mutex – Noldorin Jun 18 '09 at 23:10
  • I'd guess you're doing something wrong with the mutex; generally speaking, there would be Serious Problems if mutexes weren't doing their job. – Joe Jun 19 '09 at 02:04
  • This might be a good reference: http://stackoverflow.com/questions/975250/reliably-detecting-that-another-of-my-applications-is-running – Colin Pickard Jun 19 '09 at 09:39

2 Answers2

4

As per @Joe's comment, the problem is likely to be in the implementation of the Mutux.

This answer to another question demonstrates the right way to do it:

K. Scott Allen has a good write up on using a Mutex for this purpose and issues you'll run into with the GC.

If I want to have only one instance of the application running across all sessions on the machine, I can put the named mutex into the global namespace with the prefix “Global\”.

[STAThread]
static void Main() 
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         return;
      }

Application.Run(new Form1());
   }
}
Community
  • 1
  • 1
Colin Pickard
  • 45,724
  • 13
  • 98
  • 148
  • Thanks. I was about to post a similar question and I found this answer extremely helpful!! – bdhar Apr 30 '10 at 09:11
1

I post below link, since I could not find any related article in C++ and MFC. Therefore, For C++, MFC and Win32 you can use http://flounder.com/nomultiples.htm

baris.aydinoz
  • 1,902
  • 2
  • 18
  • 28