Restrict desktop application to single instance using MUTEX

Here is the code to restrict a desktop application to single instance (for creating single instance per user application follow the link).

The example here makes use of MUTEX to restrict the number of instances.

static void Main(string[] args)
{
            String mutexName = "MyApplication";

            Boolean createdNew;

            Mutex mutex = new Mutex(true, mutexName, out createdNew);

            if (!createdNew)
            {
                //If createdNew is false that means an instance of application is already running for this  
                // user.
                //So in this case stop the application from executing.
                return;
            }
            Console.ReadKey();
 }

In the above example replace MyApplication with your application name.

In this example we have created a Mutex named mutex, in the constructor we have supplied three arguments these are :-

     1.) initiallyOwned true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

      2.) name  - It is the name of the mutex. In our case the name of mutex is very important as we control the number of instances of the application using the mutex name. As you might have noticed I have used the application name as the mutex name so that the name remains unique for the entire system in this case you can also use a hardcoded string as the mutex name, just make sure that it won't collide with any other mutex name. Thus the mutex name for the application will be same throughout the system therefore we will not be allowed to create more than one mutex for the application thus restricting the application to have atmost one instance.

      3 .) createdNew - This argument is of out type. If the output to this parameter is true that means the mutex was not already created and it is created by this call, this implies that this is the first instance of the application on the system so we can allow it to execute further. But, if the output is false this means an instance of the application is already running on the system, so in the case stop the application from executing further

For more information about Mutex class follow the link.

No comments:

Post a Comment