4.12 Ensure That Only One Instance of an Application Can Execute Concurrently


4.12 Ensure That Only One Instance of an Application Can Execute Concurrently

Problem

You need to ensure that a user can have only one instance of an application running concurrently.

Solution

Create a named System.Threading.Mutex object and have your application try to acquire ownership of it at startup.

Discussion

The Mutex provides a mechanism for synchronizing the execution of threads across process boundaries and in addition provides a convenient mechanism through which to ensure that only a single instance of an application is running concurrently. By trying to acquire ownership of a named Mutex at startup and exiting if the Mutex can't be acquired , you can ensure that only one instance of your application is running. This example uses a Mutex named MutexExample to ensure that only a single instance of the example can execute.

 using System; using System.Threading; public class MutexExample {     public static void Main() {         // A boolean that indicates whether this application has         // initial ownership of the Mutex.         bool ownsMutex;         // Attempt to create and take ownership of a Mutex named         // MutexExample.         using (Mutex mutex =                     new Mutex(true, "MutexExample", out ownsMutex)) {             // If the application owns the Mutex it can continue to execute;             // otherwise, the application should exit.              if (ownsMutex) {                 Console.WriteLine("This application currently owns the" +                     " mutex named MutexExample. Additional instances of" +                     " this application will not run until you release" +                     " the mutex by pressing Enter.");                 Console.ReadLine();                 // Release the mutex                 mutex.ReleaseMutex();             } else {                 Console.WriteLine("Another instance of this application " +                     " already owns the mutex named MutexExample. This" +                     " instance of the application will terminate.");             }         }         // Wait to continue.         Console.WriteLine("Main method complete. Press Enter.");         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net