Allow only one instance of a Windows CE application to run at a time

Jon Skeet posted a helpful tip on How do I make sure that only one instance of my application runs at a time?. If you are running a .NET Application and are looking for how to force Windows to allow only one instance of your application to run at anytime, then I recommend you follow Skeet’s advice.

However, if you looking for a solution on how to force one-instance of your application that is targeting the .NET Compact Framework, Skeet’s post will be helpful conceptually, but the code will not work for you because of the fact that the CF version of the System.Threading.Mutex class doesn’t support the overload Mutex(bool, string, out bool).

Here’s a screenshot of the Mutex overload that Skeet uses in his example:

To work-around the limitations of CF, you can accomplish the goal by getting your hands dirty with a native call (P/Invoke) to CreateMutex(). But who’s got time for that when you can just use the free Smart Device Framework from the good guys over at OpenNETCF.

Here’s a snippet of how to make sure only one CF application is running at a time using the SDF OpenNETCF.Threading.NamedMutex() class:

    7     static class Program

    8     {

    9         /// <summary>

   10         /// The main entry point for the application.

   11         /// </summary>

   12         [MTAThread]

   13         static void Main()

   14         {

   15             bool firstInstance;

   16             //Instantiate the Mutex and give it a GUID name

   17             OpenNETCF.Threading.NamedMutex mutex =

   18                 new OpenNETCF.Threading.NamedMutex

   19                 (false,

   20                 "{50A9DA83-979B-4b6c-A095-DD1880F2B181}",

   21                 out firstInstance);


   23             //If another thread has entered the Main()

   24             //entry point, notify the user, then bail out.

   25             if (!firstInstance)

   26             {

   27                 MessageBox.Show("Form1 is already running");

   28                 return;

   29             }


   31             //Instantiate the Form application then show it

   32             Application.Run(new Form1());



   35             GC.KeepAlive(mutex);

   36         }

   37     }

Regarding the Garbage Collector call at

   35 GC.KeepAlive(mutex);

– Jon Skeet’s reasoning on this is

One thing to beware of is that the mutex isn’t garbage collected. If a local variable is only used near the start of a method, the GC may ignore it when working out which variables are garbage collection “roots” if that part of the method has already been executed. This can lead to the mutex being released earlier than you might anticipate! To prevent this from happening, make a call to GC.KeepAlive(mutex); at the end of your main method. [ref]