Dimpal Mistry
What is Mutex? How it is helpful to make single threaded job?
By Dimpal Mistry in ASP.NET on Jul 11 2011
  • Hiren V
    Jul, 2011 15

    Hi Dimple,

    A Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wide as well as application-wide.

     

    Acquiring and releasing an uncontended Mutex takes a few microseconds—about 50 times slower than a lock.

     

    With a Mutex class, you call the WaitOne method to lock and ReleaseMutex to unlock. Closing or disposing a Mutex automatically releases it. Just as with the lock statement, a Mutex can be released only from the same thread that obtained it.

     

    A common use for a cross-process Mutex is to ensure that only one instance of a program can run at a time. Here’s how

     

    it’s done:

    class OneAtATimePlease

    {

    static void Main()

    {

    // Naming a Mutex makes it available computer-wide. Use a name that's

    // unique to your company and application (e.g., include your URL).

    using (var mutex = new Mutex (false, "oreilly.com OneAtATimeDemo"))

    {

    // Wait a few seconds if contended, in case another instance

    // of the program is still in the process of shutting down.

    if (!mutex.WaitOne (TimeSpan.FromSeconds (3), false))

    {

    Console.WriteLine ("Another instance of the app is running. Bye!");

    return;

    }

    RunProgram();

    }

    }

    static void RunProgram()

    {

    Console.WriteLine ("Running. Press Enter to exit");

    Console.ReadLine();

    }

    }

     

    If running under Terminal Services, a computer-wide Mutex is ordinarily visible only to applications in the

    same terminal server session. To make it visible to all terminal server sessions, prefix its name with Global\.

     

    I hope it will be helpful for you.

     

    • 0
  • sdsd
    Jul, 2011 13

    hi....dilmple 

    mutex is a class which is use in threading
    mutex is a synchronization primitive that can also be used for interprocess synchronization
    i think this link will help u to find your answer.      
    http://msdn.microsoft.com/en-us/library/hw29w7t1%28v=vs.71%29.aspx

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS