Subscribe

RSS Feed (xml)

Showing posts with label Ensure That Only One Instance of an Application Can Execute Concurrently. Show all posts
Showing posts with label Ensure That Only One Instance of an Application Can Execute Concurrently. Show all posts

Ensure That Only One Instance of an Application Can Execute Concurrently

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();
    }
}

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail