Thursday, February 10, 2005

Mutex - 2

Mutex (with name)
Named Mutex works across applications. A named Mutex is created by its overloaded constructor
public Mutex(bool initiallyOwned , string name)
The first argument specifies whether the calling thread receives the initial ownership of the Mutex.

The second string argument is the name for this mutex. “If name is not null and initiallyOwned is true, then the application must ensure that a mutex (that has the same name and is owned by the calling thread) does not already exist. If the mutex is being used for cross-process communication, you should set initiallyOwned to false, or use the Mutex(Boolean, String, Boolean) constructor. Otherwise, it will be difficult to determine which process has initial ownership.” (from MSDN “Mutex Constructor (Boolean, String)” )


The below code shows a great way how mutex can be used:


using System;
using System.Threading;
public class TestMutex

{
public static void Main()
{
// Create the named mutex. Only one system object named
// "MyMutex" can exist; the local Mutex object represents
// this system object, regardless of which process or thread
// caused "MyMutex" to be created.

Mutex m = new Mutex(false, "MyMutex");
// Try to gain control of the named mutex. If the mutex is
// controlled by another thread, wait for it to be released.

Console.WriteLine("Waiting for the Mutex.");
m.WaitOne();
// Keep control of the mutex until the user presses
// ENTER.

Console.WriteLine("This application owns the mutex. " + "Press ENTER to release the mutex and exit.");
Console.ReadLine();
m.ReleaseMutex();
}

}
// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named
// mutex is destroyed when all the Mutex objects that represent it
// have been released.
// The constructor overload shown here cannot tell the calling thread
// whether initial ownership of the named mutex was granted. Therefore,
// do not request initial ownership unless you are certain that the
// thread will create the named mutex.

0 Comments:

Post a Comment

<< Home