Welcome to MSDN Blogs Sign in | Join | Help

SYSK 210: Cross-Process Synchronization

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

            }

        }

    }

}

 

Published Tuesday, October 03, 2006 5:35 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: SYSK 210: Cross-Process Synchronization

Thursday, October 12, 2006 9:03 AM by Alexey Kuznetsov

This line:

bool success = false;

shows all the thoroughness of the programmer :) I like it so much when the code looks that way!

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker