Este artículo proviene de un motor de traducción automática. Mueva el puntero sobre las frases del artículo para ver el texto original. Más información.
Traducción
Original
Este tema aún no ha recibido ninguna valoración - Valorar este tema

EventWaitHandle.SetAccessControl (Método)

Establece la seguridad de control de acceso para un evento del sistema con nombre.

Espacio de nombres:  System.Threading
Ensamblado:  mscorlib (en mscorlib.dll)
public void SetAccessControl(
	EventWaitHandleSecurity eventSecurity
)

Parámetros

eventSecurity
Tipo: System.Security.AccessControl.EventWaitHandleSecurity
Objeto EventWaitHandleSecurity que representa la seguridad de control de acceso que se va a aplicar al evento del sistema con nombre.
ExcepciónCondición
ArgumentNullException

eventSecurity es null.

UnauthorizedAccessException

El usuario no tiene EventWaitHandleRights.ChangePermissions.

O bien

El evento no se ha abierto con EventWaitHandleRights.ChangePermissions.

SystemException

El objeto EventWaitHandle actual no representa un evento del sistema con nombre.

ObjectDisposedException

Se llamó al método Close previamente en System.Threading.EventWaitHandle.

El usuario necesita tener derechos EventWaitHandleRights.ChangePermissions para llamar a este método y el evento se debe haber abierto con el marcador EventWaitHandleRights.ChangePermissions.

En el ejemplo de código siguiente se muestra el comportamiento entre procesos de un evento del sistema con nombre y con seguridad de control de acceso. En el ejemplo se utiliza la sobrecarga del método OpenExisting(String) para comprobar la existencia de un evento con nombre.

Si el evento no existe, se crea con la propiedad inicial y con seguridad de control de acceso que niega al usuario actual el derecho a utilizar el evento, pero le concede el derecho a leer y cambiar permisos en el evento.

Si el ejemplo compilado se ejecuta desde dos ventanas de comandos, la segunda copia producirá una excepción de infracción de acceso en la llamada a OpenExisting(String). La excepción se detecta, y en el ejemplo se utiliza la sobrecarga del método OpenExisting(String, EventWaitHandleRights) para esperar en el evento con los derechos necesarios para leer y cambiar los permisos.

Una vez cambiados los permisos, mediante el método SetAccessControl, el evento se abre con los derechos necesarios para esperar en él y señalarlo. Si el ejemplo compilado se ejecuta desde una tercera ventana de comandos, el ejemplo se ejecutará utilizando los nuevos permisos.


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

internal class Example
{
    internal static void Main()
    {
        const string ewhName = "EventWaitHandleExample5";

        EventWaitHandle ewh = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

        // Attempt to open the named event.
        try
        {
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), to wait on and 
            // signal the named event.
            //
            ewh = EventWaitHandle.OpenExisting(ewhName);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Named event does not exist.");
            doesNotExist = true;
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

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

            // Create an access control list (ACL) that denies the
            // current user the right to wait on or signal the 
            // event, but allows the right to read and change
            // security information for the event.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            EventWaitHandleSecurity ewhSec = 
                new EventWaitHandleSecurity();

            EventWaitHandleAccessRule rule = 
                new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Deny);
            ewhSec.AddAccessRule(rule);

            rule = new EventWaitHandleAccessRule(user, 
                EventWaitHandleRights.ReadPermissions | 
                EventWaitHandleRights.ChangePermissions, 
                AccessControlType.Allow);
            ewhSec.AddAccessRule(rule);

            // Create an EventWaitHandle object that represents
            // the system event named by the constant 'ewhName', 
            // initially signaled, with automatic reset, and with
            // the specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in wasCreated.
            //
            ewh = new EventWaitHandle(true, 
                EventResetMode.AutoReset, 
                ewhName, 
                out wasCreated, 
                ewhSec);

            // If the named system event 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 event. Otherwise, exit the program.
            // 
            if (wasCreated)
            {
                Console.WriteLine("Created the named event.");
            }
            else
            {
                Console.WriteLine("Unable to create the event.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the event to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                ewh = EventWaitHandle.OpenExisting(ewhName, 
                    EventWaitHandleRights.ReadPermissions | 
                    EventWaitHandleRights.ChangePermissions);

                // Get the current ACL. This requires 
                // EventWaitHandleRights.ReadPermissions.
                EventWaitHandleSecurity ewhSec = ewh.GetAccessControl();

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

                // First, the rule that denied the current user 
                // the right to enter and release the event must
                // be removed.
                EventWaitHandleAccessRule rule = 
                    new EventWaitHandleAccessRule(user, 
                        EventWaitHandleRights.Synchronize | 
                        EventWaitHandleRights.Modify, 
                        AccessControlType.Deny);
                ewhSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Allow);
                ewhSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec);

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

                // Open the event with (EventWaitHandleRights.Synchronize 
                // | EventWaitHandleRights.Modify), the rights required
                // to wait on and signal the event.
                //
                ewh = EventWaitHandle.OpenExisting(ewhName);

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

        }

        // Wait on the event, and hold it until the program
        // exits.
        //
        try
        {
            Console.WriteLine("Wait on the event.");
            ewh.WaitOne();
            Console.WriteLine("Event was signaled.");
            Console.WriteLine("Press the Enter key to signal the event and exit.");
            Console.ReadLine();
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
        finally
        {
            ewh.Set();
        }
    }
}


.NET Framework

Compatible con: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (no se admite el rol Server Core), Windows Server 2008 R2 (se admite el rol Server Core con SP1 o versiones posteriores; no se admite Itanium)

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Fecha

Historial

Motivo

Septiembre de 2010

Agregada excepción que faltaba.

Comentarios de los clientes.

¿Te ha resultado útil?
(Caracteres restantes: 1500)

Adiciones de comunidad

AGREGAR
© 2013 Microsoft. Reservados todos los derechos.