Say you need to prevent two pieces of code from running at the same time.  If you’re dealing with two threads in the same application domain, then it’s easy – you’ve got many synchronization objects to choose from for the job such as  System.Threading.Monitor, System.Threading.ReaderWriterLock, System.Threading.Semaphore, System.Threading.Mutex.

 

However, since handles are process specific, you can not use same objects to synchronize across processes.  Say, for example, you need to disallow multiple instances of your application from being launched.  Or, perhaps, you have a memory mapped file accessed by multiple instances of a process running on the same server, and you need to synchronize access to this resource.  How would you approach these problems?  By using named synchronization objects such as named mutex (for mutual exclusion).

 

Below is an example of using a named mutex for preventing a user from running multiple instances of your application:

static class Program

{

    /// <summary>

    /// The main entry point for the application.

    /// </summary>

    [STAThread]

    static void Main()

    {           

        Application.EnableVisualStyles();

        Application.SetCompatibleTextRenderingDefault(false);

 

        bool success = false;

        using (System.Threading.Mutex m = new System.Threading.Mutex(true, "WinApp1", out success))

        {

            if (success)

            {

                Application.Run(new Form1());

            }

            else

            {

                MessageBox.Show("Only one instance of WindowsApplication1 is allowed");

                // TODO: Consider finding the running instance and bringing it to top of Z-order

            }

        }

    }

}