Questo articolo è stato tradotto automaticamente. Per visualizzare l'articolo in inglese, selezionare la casella di controllo Inglese. È possibile anche visualizzare il testo inglese in una finestra popup posizionando il puntatore del mouse sopra il testo.
Traduzione
Inglese

Costruttore Mutex (Boolean, String, Boolean, MutexSecurity)

 

Inizializza una nuova istanza della classe Mutex con un valore booleano che indica se il thread chiamante deve avere la proprietà iniziale del mutex, con una stringa che rappresenta il nome del mutex, con una variabile Boolean che, quando il metodo viene restituito, indichi se al thread chiamante era stata concessa la proprietà iniziale del mutex e con la sicurezza del controllo di accesso da applicare al mutex denominato.

Spazio dei nomi:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

[SecurityCriticalAttribute]
public Mutex(
	bool initiallyOwned,
	string name,
	out bool createdNew,
	MutexSecurity mutexSecurity
)

Parametri

initiallyOwned
Type: System.Boolean

true per concedere al thread chiamante la proprietà iniziale del mutex di sistema denominato, se questo è stato creato come risultato della chiamata; in caso contrario, false.

name
Type: System.String

Nome del mutex di sistema. Se il valore è null, l'oggetto Mutex è senza nome.

createdNew
Type: System.Boolean

Quando questo metodo viene restituito, contiene un valore booleano che è true se è stato creato un mutex locale (ovvero, se il valore di name è null o una stringa vuota) oppure se è stato creato il mutex di sistema denominato specificato; false se il mutex di sistema denominato specificato è già esistente. Questo parametro viene passato non inizializzato.

mutexSecurity
Type: System.Security.AccessControl.MutexSecurity

Oggetto MutexSecurity che rappresenta la sicurezza del controllo di accesso da applicare al mutex di sistema denominato.

Exception Condition
IOException

Errore Win32.

UnauthorizedAccessException

Il mutex denominato esiste e ha accesso alla sicurezza controllo, ma l'utente non dispone di MutexRights.FullControl.

WaitHandleCannotBeOpenedException

Il mutex denominato non può essere creato, forse perché un handle di attesa di un tipo diverso ha lo stesso nome.

ArgumentException

La lunghezza di name supera i 260 caratteri.

If name is not null and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. Otherwise the thread can request the mutex by calling the Overload:System.Threading.WaitHandle.WaitOne method.

Use this constructor to apply access control security to a named system mutex when it is created, preventing other code from taking control of the mutex.

This constructor initializes a T:System.Threading.Mutex object that represents a named system mutex. You can create multiple T:System.Threading.Mutex objects that represent the same named system mutex.

If the named system mutex does not exist, it is created with the specified access control security. If the named mutex exists, the specified access control security is ignored.

System_CAPS_noteNota

The caller has full control over the newly created T:System.Threading.Mutex object even if mutexSecurity denies or fails to grant some access rights to the current user. However, if the current user attempts to get another T:System.Threading.Mutex object to represent the same named mutex, using either a constructor or the Overload:System.Threading.Mutex.OpenExisting method, Windows access control security is applied.

If the named mutex has already been created with access control security, and the caller does not have F:System.Security.AccessControl.MutexRights.FullControl, an exception is thrown. To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the Overload:System.Threading.Mutex.OpenExisting method.

If you specify null or an empty string for name, a local mutex is created, as if you had called the M:System.Threading.Mutex.#ctor(System.Boolean) constructor. In this case, createdNew is always true.

Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

System_CAPS_noteNota

On a server that is running Terminal Services, a named system mutex can have two levels of visibility. If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

The following code example demonstrates the cross-process behavior of a named mutex with access control security. The example uses the M:System.Threading.Mutex.OpenExisting(System.String) method overload to test for the existence of a named mutex.

If the mutex does not exist, it is created with initial ownership and access control security that denies the current user the right to use the mutex, but grants the right to read and change permissions on the mutex.

If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to M:System.Threading.Mutex.OpenExisting(System.String). The exception is caught, and the example uses the M:System.Threading.Mutex.OpenExisting(System.String,System.Security.AccessControl.MutexRights) method overload to open the mutex with the rights needed to read and change the permissions.

After the permissions are changed, the mutex is opened with the rights required to enter and release it. If you run the compiled example from a third command window, it runs using the new permissions.

using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string mutexName = "MutexExample4";

        Mutex m = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the mutex
        // constructor. It is true if the named system mutex was
        // created, and false if the named mutex already existed.
        //
        bool mutexWasCreated = false;

        // Attempt to open the named mutex.
        try
        {
            // Open the mutex with (MutexRights.Synchronize |
            // MutexRights.Modify), to enter and release the
            // named mutex.
            //
            m = Mutex.OpenExisting(mutexName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Mutex does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The mutex does not exist.
        // (2) The mutex exists, but the current user doesn't 
        // have access. (3) The mutex exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The mutex does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to enter or release the 
            // mutex, but allows the right to read and change
            // security information for the mutex.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            MutexSecurity mSec = new MutexSecurity();

            MutexAccessRule rule = new MutexAccessRule(user, 
                MutexRights.Synchronize | MutexRights.Modify, 
                AccessControlType.Deny);
            mSec.AddAccessRule(rule);

            rule = new MutexAccessRule(user, 
                MutexRights.ReadPermissions | MutexRights.ChangePermissions,
                AccessControlType.Allow);
            mSec.AddAccessRule(rule);

            // Create a Mutex object that represents the system
            // mutex named by the constant 'mutexName', with
            // initial ownership for this thread, and with the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in mutexWasCreated.
            //
            m = new Mutex(true, mutexName, out mutexWasCreated, mSec);

            // If the named system mutex was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the mutex. Otherwise, exit the program.
            // 
            if (mutexWasCreated)
            {
                Console.WriteLine("Created the mutex.");
            }
            else
            {
                Console.WriteLine("Unable to create the mutex.");
                return;
            }

        }
        else if (unauthorized)
        {
            // Open the mutex to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                m = Mutex.OpenExisting(mutexName, 
                    MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                // Get the current ACL. This requires 
                // MutexRights.ReadPermissions.
                MutexSecurity mSec = m.GetAccessControl();

                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the mutex must
                // be removed.
                MutexAccessRule rule = new MutexAccessRule(user, 
                     MutexRights.Synchronize | MutexRights.Modify,
                     AccessControlType.Deny);
                mSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new MutexAccessRule(user, 
                    MutexRights.Synchronize | MutexRights.Modify,
                    AccessControlType.Allow);
                mSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // MutexRights.ChangePermissions.
                m.SetAccessControl(mSec);

                Console.WriteLine("Updated mutex security.");

                // Open the mutex with (MutexRights.Synchronize 
                // | MutexRights.Modify), the rights required to
                // enter and release the mutex.
                //
                m = Mutex.OpenExisting(mutexName);

            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }

        }

        // If this program created the mutex, it already owns
        // the mutex.
        //
        if (!mutexWasCreated)
        {
            // Enter the mutex, and hold it until the program
            // exits.
            //
            try
            {
                Console.WriteLine("Wait for the mutex.");
                m.WaitOne();
                Console.WriteLine("Entered the mutex.");
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unauthorized access: {0}", ex.Message);
            }
        }

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadLine();
        m.ReleaseMutex();
        m.Dispose();
    }
}

SecurityCriticalAttribute

Requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

.NET Framework
Disponibile da 2.0
Torna all'inizio
Mostra: