Semaphore.OpenExisting Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Apre un semaforo denominato specificato, se esiste già.
Overload
| Nome | Descrizione |
|---|---|
| OpenExisting(String) |
Apre il semaforo denominato specificato, se già esistente. |
| OpenExisting(String, SemaphoreRights) |
Apre il semaforo denominato specificato, se già esistente, con l'accesso di sicurezza desiderato. |
| OpenExisting(String, NamedWaitHandleOptions) |
Apre il semaforo denominato specificato, se già esistente. Se le opzioni sono impostate solo sull'utente corrente, i controlli di accesso dell'oggetto vengono verificati per l'utente chiamante. |
OpenExisting(String)
- Origine:
- Semaphore.cs
- Origine:
- Semaphore.cs
- Origine:
- Semaphore.cs
- Origine:
- Semaphore.cs
- Origine:
- Semaphore.cs
Apre il semaforo denominato specificato, se già esistente.
public:
static System::Threading::Semaphore ^ OpenExisting(System::String ^ name);
public static System.Threading.Semaphore OpenExisting(string name);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static System.Threading.Semaphore OpenExisting(string name);
static member OpenExisting : string -> System.Threading.Semaphore
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
static member OpenExisting : string -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String) As Semaphore
Parametri
- name
- String
Nome dell'oggetto di sincronizzazione da condividere con altri processi. Il nome fa distinzione tra maiuscole e minuscole. Il carattere barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni. Potrebbero esserci ulteriori restrizioni sul nome a seconda del sistema operativo. Ad esempio, nei sistemi operativi basati su Unix, il nome dopo l'esclusione dello spazio dei nomi deve essere un nome di file valido.
Valori restituiti
Oggetto che rappresenta il semaforo di sistema denominato.
- Attributi
Eccezioni
name è una stringa vuota.
oppure
solo .NET Framework: name è più lungo di MAX_PATH (260 caratteri).
name è null.
Impossibile creare un oggetto di sincronizzazione con l'oggetto specificato name . Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome. In alcuni casi, questa eccezione può essere generata per nomi non validi.
name non è valido. Questo può essere per vari motivi, incluse alcune restrizioni che potrebbero essere inserite dal sistema operativo, ad esempio un prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" fanno distinzione tra maiuscole e minuscole.
oppure
Si è verificato un altro errore. La HResult proprietà potrebbe fornire altre informazioni.
name supera la lunghezza consentita. Le restrizioni relative alla lunghezza possono dipendere dal sistema operativo o dalla configurazione.
Il semaforo denominato esiste, ma l'utente non ha l'accesso di sicurezza necessario per usarlo.
Esempio
Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un semaforo denominato con sicurezza del controllo di accesso. Nell'esempio viene usato l'overload del OpenExisting(String) metodo per verificare l'esistenza di un semaforo denominato.
Se il semaforo non esiste, viene creato con un numero massimo di due e con la sicurezza del controllo di accesso che nega all'utente corrente il diritto di usare il semaforo, ma che concede il diritto di leggere e modificare le autorizzazioni per il semaforo.
Se si esegue l'esempio compilato da due finestre di comando, la seconda copia genererà un'eccezione di violazione di accesso nella chiamata all'overload del OpenExisting(String) metodo. L'eccezione viene intercettata e l'esempio usa l'overload del OpenExisting(String, SemaphoreRights) metodo per aprire il semaforo con i diritti necessari per leggere e modificare le autorizzazioni.
Dopo aver modificato le autorizzazioni, il semaforo viene aperto con i diritti necessari per immetterlo e rilasciarlo. Se si esegue l'esempio compilato da una terza finestra di comando, viene eseguito usando le nuove autorizzazioni.
using System;
using System.Threading;
using System.Security.AccessControl;
internal class Example
{
internal static void Main()
{
const string semaphoreName = "SemaphoreExample5";
Semaphore sem = null;
bool doesNotExist = false;
bool unauthorized = false;
// Attempt to open the named semaphore.
try
{
// Open the semaphore with (SemaphoreRights.Synchronize
// | SemaphoreRights.Modify), to enter and release the
// named semaphore.
//
sem = Semaphore.OpenExisting(semaphoreName);
}
catch(WaitHandleCannotBeOpenedException)
{
Console.WriteLine("Semaphore does not exist.");
doesNotExist = true;
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unauthorized access: {0}", ex.Message);
unauthorized = true;
}
// There are three cases: (1) The semaphore does not exist.
// (2) The semaphore exists, but the current user doesn't
// have access. (3) The semaphore exists and the user has
// access.
//
if (doesNotExist)
{
// The semaphore does not exist, so create it.
//
// The value of this variable is set by the semaphore
// constructor. It is true if the named system semaphore was
// created, and false if the named semaphore already existed.
//
bool semaphoreWasCreated;
// Create an access control list (ACL) that denies the
// current user the right to enter or release the
// semaphore, but allows the right to read and change
// security information for the semaphore.
//
string user = Environment.UserDomainName + "\\"
+ Environment.UserName;
SemaphoreSecurity semSec = new SemaphoreSecurity();
SemaphoreAccessRule rule = new SemaphoreAccessRule(
user,
SemaphoreRights.Synchronize | SemaphoreRights.Modify,
AccessControlType.Deny);
semSec.AddAccessRule(rule);
rule = new SemaphoreAccessRule(
user,
SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
AccessControlType.Allow);
semSec.AddAccessRule(rule);
// Create a Semaphore object that represents the system
// semaphore named by the constant 'semaphoreName', with
// maximum count three, initial count three, and the
// specified security access. The Boolean value that
// indicates creation of the underlying system object is
// placed in semaphoreWasCreated.
//
sem = new Semaphore(3, 3, semaphoreName,
out semaphoreWasCreated, semSec);
// If the named system semaphore was created, it can be
// used by the current instance of this program, even
// though the current user is denied access. The current
// program enters the semaphore. Otherwise, exit the
// program.
//
if (semaphoreWasCreated)
{
Console.WriteLine("Created the semaphore.");
}
else
{
Console.WriteLine("Unable to create the semaphore.");
return;
}
}
else if (unauthorized)
{
// Open the semaphore to read and change the access
// control security. The access control security defined
// above allows the current user to do this.
//
try
{
sem = Semaphore.OpenExisting(
semaphoreName,
SemaphoreRights.ReadPermissions
| SemaphoreRights.ChangePermissions);
// Get the current ACL. This requires
// SemaphoreRights.ReadPermissions.
SemaphoreSecurity semSec = sem.GetAccessControl();
string user = Environment.UserDomainName + "\\"
+ Environment.UserName;
// First, the rule that denied the current user
// the right to enter and release the semaphore must
// be removed.
SemaphoreAccessRule rule = new SemaphoreAccessRule(
user,
SemaphoreRights.Synchronize | SemaphoreRights.Modify,
AccessControlType.Deny);
semSec.RemoveAccessRule(rule);
// Now grant the user the correct rights.
//
rule = new SemaphoreAccessRule(user,
SemaphoreRights.Synchronize | SemaphoreRights.Modify,
AccessControlType.Allow);
semSec.AddAccessRule(rule);
// Update the ACL. This requires
// SemaphoreRights.ChangePermissions.
sem.SetAccessControl(semSec);
Console.WriteLine("Updated semaphore security.");
// Open the semaphore with (SemaphoreRights.Synchronize
// | SemaphoreRights.Modify), the rights required to
// enter and release the semaphore.
//
sem = Semaphore.OpenExisting(semaphoreName);
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unable to change permissions: {0}", ex.Message);
return;
}
}
// Enter the semaphore, and hold it until the program
// exits.
//
try
{
sem.WaitOne();
Console.WriteLine("Entered the semaphore.");
Console.WriteLine("Press the Enter key to exit.");
Console.ReadLine();
sem.Release();
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unauthorized access: {0}", ex.Message);
}
}
}
Imports System.Threading
Imports System.Security.AccessControl
Friend Class Example
<MTAThread> _
Friend Shared Sub Main()
Const semaphoreName As String = "SemaphoreExample5"
Dim sem As Semaphore = Nothing
Dim doesNotExist as Boolean = False
Dim unauthorized As Boolean = False
' Attempt to open the named semaphore.
Try
' Open the semaphore with (SemaphoreRights.Synchronize
' Or SemaphoreRights.Modify), to enter and release the
' named semaphore.
'
sem = Semaphore.OpenExisting(semaphoreName)
Catch ex As WaitHandleCannotBeOpenedException
Console.WriteLine("Semaphore does not exist.")
doesNotExist = True
Catch ex As UnauthorizedAccessException
Console.WriteLine("Unauthorized access: {0}", ex.Message)
unauthorized = True
End Try
' There are three cases: (1) The semaphore does not exist.
' (2) The semaphore exists, but the current user doesn't
' have access. (3) The semaphore exists and the user has
' access.
'
If doesNotExist Then
' The semaphore does not exist, so create it.
'
' The value of this variable is set by the semaphore
' constructor. It is True if the named system semaphore was
' created, and False if the named semaphore already existed.
'
Dim semaphoreWasCreated As Boolean
' Create an access control list (ACL) that denies the
' current user the right to enter or release the
' semaphore, but allows the right to read and change
' security information for the semaphore.
'
Dim user As String = Environment.UserDomainName _
& "\" & Environment.UserName
Dim semSec As New SemaphoreSecurity()
Dim rule As New SemaphoreAccessRule(user, _
SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
AccessControlType.Deny)
semSec.AddAccessRule(rule)
rule = New SemaphoreAccessRule(user, _
SemaphoreRights.ReadPermissions Or _
SemaphoreRights.ChangePermissions, _
AccessControlType.Allow)
semSec.AddAccessRule(rule)
' Create a Semaphore object that represents the system
' semaphore named by the constant 'semaphoreName', with
' maximum count three, initial count three, and the
' specified security access. The Boolean value that
' indicates creation of the underlying system object is
' placed in semaphoreWasCreated.
'
sem = New Semaphore(3, 3, semaphoreName, _
semaphoreWasCreated, semSec)
' If the named system semaphore was created, it can be
' used by the current instance of this program, even
' though the current user is denied access. The current
' program enters the semaphore. Otherwise, exit the
' program.
'
If semaphoreWasCreated Then
Console.WriteLine("Created the semaphore.")
Else
Console.WriteLine("Unable to create the semaphore.")
Return
End If
ElseIf unauthorized Then
' Open the semaphore to read and change the access
' control security. The access control security defined
' above allows the current user to do this.
'
Try
sem = Semaphore.OpenExisting(semaphoreName, _
SemaphoreRights.ReadPermissions Or _
SemaphoreRights.ChangePermissions)
' Get the current ACL. This requires
' SemaphoreRights.ReadPermissions.
Dim semSec As SemaphoreSecurity = sem.GetAccessControl()
Dim user As String = Environment.UserDomainName _
& "\" & Environment.UserName
' First, the rule that denied the current user
' the right to enter and release the semaphore must
' be removed.
Dim rule As New SemaphoreAccessRule(user, _
SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
AccessControlType.Deny)
semSec.RemoveAccessRule(rule)
' Now grant the user the correct rights.
'
rule = New SemaphoreAccessRule(user, _
SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
AccessControlType.Allow)
semSec.AddAccessRule(rule)
' Update the ACL. This requires
' SemaphoreRights.ChangePermissions.
sem.SetAccessControl(semSec)
Console.WriteLine("Updated semaphore security.")
' Open the semaphore with (SemaphoreRights.Synchronize
' Or SemaphoreRights.Modify), the rights required to
' enter and release the semaphore.
'
sem = Semaphore.OpenExisting(semaphoreName)
Catch ex As UnauthorizedAccessException
Console.WriteLine("Unable to change permissions: {0}", _
ex.Message)
Return
End Try
End If
' Enter the semaphore, and hold it until the program
' exits.
'
Try
sem.WaitOne()
Console.WriteLine("Entered the semaphore.")
Console.WriteLine("Press the Enter key to exit.")
Console.ReadLine()
sem.Release()
Catch ex As UnauthorizedAccessException
Console.WriteLine("Unauthorized access: {0}", _
ex.Message)
End Try
End Sub
End Class
Commenti
Può name essere preceduto Global\ da o Local\ per specificare uno spazio dei nomi. Quando si specifica lo Global spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con qualsiasi processo nel sistema. Quando si specifica lo Local spazio dei nomi , che è anche l'impostazione predefinita quando non viene specificato alcuno spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con i processi nella stessa sessione. In Windows una sessione è una sessione di accesso e i servizi vengono in genere eseguiti in una sessione non interattiva diversa. Nei sistemi operativi simili a Unix, ogni shell ha una propria sessione. Gli oggetti di sincronizzazione locale della sessione possono essere appropriati per la sincronizzazione tra processi con una relazione padre/figlio in cui vengono eseguiti tutti nella stessa sessione. Per altre informazioni sui nomi degli oggetti di sincronizzazione in Windows, vedere Nomina oggetto.
Se esiste un oggetto di sincronizzazione del tipo richiesto nello spazio dei nomi , viene aperto l'oggetto di sincronizzazione esistente. Se non esiste un oggetto di sincronizzazione nello spazio dei nomi o un oggetto di sincronizzazione di un tipo diverso esiste nello spazio dei nomi , viene generato un oggetto WaitHandleCannotBeOpenedException .
Il OpenExisting metodo tenta di aprire il semaforo denominato specificato. Per creare il semaforo di sistema quando non esiste già, usare uno dei Semaphore costruttori con un name parametro .
Più chiamate a questo metodo che utilizzano lo stesso valore per name non restituiscono necessariamente lo stesso Semaphore oggetto, anche se gli oggetti restituiti rappresentano lo stesso semaforo di sistema denominato.
Questo overload del metodo equivale a chiamare l'overload del OpenExisting metodo e specificare SemaphoreRights.Synchronize i diritti e SemaphoreRights.Modify , combinati usando l'operazione OR bit per bit.
Se si specifica il SemaphoreRights.Synchronize flag, un thread può immettere il semaforo e specificare il SemaphoreRights.Modify flag consente a un thread di chiamare il Release metodo .
Vedi anche
- di threading gestito
- Semaforo
Si applica a
OpenExisting(String, SemaphoreRights)
Apre il semaforo denominato specificato, se già esistente, con l'accesso di sicurezza desiderato.
public:
static System::Threading::Semaphore ^ OpenExisting(System::String ^ name, System::Security::AccessControl::SemaphoreRights rights);
public static System.Threading.Semaphore OpenExisting(string name, System.Security.AccessControl.SemaphoreRights rights);
static member OpenExisting : string * System.Security.AccessControl.SemaphoreRights -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String, rights As SemaphoreRights) As Semaphore
Parametri
- name
- String
Nome dell'oggetto di sincronizzazione da condividere con altri processi. Il nome fa distinzione tra maiuscole e minuscole. Il carattere barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni. Potrebbero esserci ulteriori restrizioni sul nome a seconda del sistema operativo. Ad esempio, nei sistemi operativi basati su Unix, il nome dopo l'esclusione dello spazio dei nomi deve essere un nome di file valido.
- rights
- SemaphoreRights
Combinazione bit per bit dei valori di enumerazione che rappresentano l'accesso alla sicurezza desiderato.
Valori restituiti
Oggetto che rappresenta il semaforo di sistema denominato.
Eccezioni
name è una stringa vuota.
oppure
solo .NET Framework: name è più lungo di MAX_PATH (260 caratteri).
name è null.
Impossibile creare un oggetto di sincronizzazione con l'oggetto specificato name . Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome. In alcuni casi, questa eccezione può essere generata per nomi non validi.
name non è valido. Questo può essere per vari motivi, incluse alcune restrizioni che potrebbero essere inserite dal sistema operativo, ad esempio un prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" fanno distinzione tra maiuscole e minuscole.
oppure
Si è verificato un altro errore. La HResult proprietà potrebbe fornire altre informazioni.
name supera la lunghezza consentita. Le restrizioni relative alla lunghezza possono dipendere dal sistema operativo o dalla configurazione.
Il semaforo denominato esiste, ma l'utente non dispone dei diritti di accesso alla sicurezza desiderati.
Esempio
Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un semaforo denominato con sicurezza del controllo di accesso. Nell'esempio viene usato l'overload del OpenExisting(String) metodo per verificare l'esistenza di un semaforo denominato.
Se il semaforo non esiste, viene creato con un conteggio massimo di due e con la sicurezza del controllo di accesso che nega all'utente corrente il diritto di usare il semaforo, ma concede il diritto di leggere e modificare le autorizzazioni per il semaforo.
Se si esegue l'esempio compilato da due finestre di comando, la seconda copia genererà un'eccezione di violazione di accesso nella chiamata al OpenExisting(String) metodo . L'eccezione viene intercettata e l'esempio usa l'overload del OpenExisting(String, SemaphoreRights) metodo per aprire il semaforo con i diritti necessari per leggere e modificare le autorizzazioni.
Dopo aver modificato le autorizzazioni, il semaforo viene aperto con i diritti necessari per immetterlo e rilasciarlo. Se si esegue l'esempio compilato da una terza finestra di comando, viene eseguito usando le nuove autorizzazioni.
using System;
using System.Threading;
using System.Security.AccessControl;
internal class Example
{
internal static void Main()
{
const string semaphoreName = "SemaphoreExample5";
Semaphore sem = null;
bool doesNotExist = false;
bool unauthorized = false;
// Attempt to open the named semaphore.
try
{
// Open the semaphore with (SemaphoreRights.Synchronize
// | SemaphoreRights.Modify), to enter and release the
// named semaphore.
//
sem = Semaphore.OpenExisting(semaphoreName);
}
catch(WaitHandleCannotBeOpenedException)
{
Console.WriteLine("Semaphore does not exist.");
doesNotExist = true;
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unauthorized access: {0}", ex.Message);
unauthorized = true;
}
// There are three cases: (1) The semaphore does not exist.
// (2) The semaphore exists, but the current user doesn't
// have access. (3) The semaphore exists and the user has
// access.
//
if (doesNotExist)
{
// The semaphore does not exist, so create it.
//
// The value of this variable is set by the semaphore
// constructor. It is true if the named system semaphore was
// created, and false if the named semaphore already existed.
//
bool semaphoreWasCreated;
// Create an access control list (ACL) that denies the
// current user the right to enter or release the
// semaphore, but allows the right to read and change
// security information for the semaphore.
//
string user = Environment.UserDomainName + "\\"
+ Environment.UserName;
SemaphoreSecurity semSec = new SemaphoreSecurity();
SemaphoreAccessRule rule = new SemaphoreAccessRule(
user,
SemaphoreRights.Synchronize | SemaphoreRights.Modify,
AccessControlType.Deny);
semSec.AddAccessRule(rule);
rule = new SemaphoreAccessRule(
user,
SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
AccessControlType.Allow);
semSec.AddAccessRule(rule);
// Create a Semaphore object that represents the system
// semaphore named by the constant 'semaphoreName', with
// maximum count three, initial count three, and the
// specified security access. The Boolean value that
// indicates creation of the underlying system object is
// placed in semaphoreWasCreated.
//
sem = new Semaphore(3, 3, semaphoreName,
out semaphoreWasCreated, semSec);
// If the named system semaphore was created, it can be
// used by the current instance of this program, even
// though the current user is denied access. The current
// program enters the semaphore. Otherwise, exit the
// program.
//
if (semaphoreWasCreated)
{
Console.WriteLine("Created the semaphore.");
}
else
{
Console.WriteLine("Unable to create the semaphore.");
return;
}
}
else if (unauthorized)
{
// Open the semaphore to read and change the access
// control security. The access control security defined
// above allows the current user to do this.
//
try
{
sem = Semaphore.OpenExisting(
semaphoreName,
SemaphoreRights.ReadPermissions
| SemaphoreRights.ChangePermissions);
// Get the current ACL. This requires
// SemaphoreRights.ReadPermissions.
SemaphoreSecurity semSec = sem.GetAccessControl();
string user = Environment.UserDomainName + "\\"
+ Environment.UserName;
// First, the rule that denied the current user
// the right to enter and release the semaphore must
// be removed.
SemaphoreAccessRule rule = new SemaphoreAccessRule(
user,
SemaphoreRights.Synchronize | SemaphoreRights.Modify,
AccessControlType.Deny);
semSec.RemoveAccessRule(rule);
// Now grant the user the correct rights.
//
rule = new SemaphoreAccessRule(user,
SemaphoreRights.Synchronize | SemaphoreRights.Modify,
AccessControlType.Allow);
semSec.AddAccessRule(rule);
// Update the ACL. This requires
// SemaphoreRights.ChangePermissions.
sem.SetAccessControl(semSec);
Console.WriteLine("Updated semaphore security.");
// Open the semaphore with (SemaphoreRights.Synchronize
// | SemaphoreRights.Modify), the rights required to
// enter and release the semaphore.
//
sem = Semaphore.OpenExisting(semaphoreName);
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unable to change permissions: {0}", ex.Message);
return;
}
}
// Enter the semaphore, and hold it until the program
// exits.
//
try
{
sem.WaitOne();
Console.WriteLine("Entered the semaphore.");
Console.WriteLine("Press the Enter key to exit.");
Console.ReadLine();
sem.Release();
}
catch(UnauthorizedAccessException ex)
{
Console.WriteLine("Unauthorized access: {0}", ex.Message);
}
}
}
Imports System.Threading
Imports System.Security.AccessControl
Friend Class Example
<MTAThread> _
Friend Shared Sub Main()
Const semaphoreName As String = "SemaphoreExample5"
Dim sem As Semaphore = Nothing
Dim doesNotExist as Boolean = False
Dim unauthorized As Boolean = False
' Attempt to open the named semaphore.
Try
' Open the semaphore with (SemaphoreRights.Synchronize
' Or SemaphoreRights.Modify), to enter and release the
' named semaphore.
'
sem = Semaphore.OpenExisting(semaphoreName)
Catch ex As WaitHandleCannotBeOpenedException
Console.WriteLine("Semaphore does not exist.")
doesNotExist = True
Catch ex As UnauthorizedAccessException
Console.WriteLine("Unauthorized access: {0}", ex.Message)
unauthorized = True
End Try
' There are three cases: (1) The semaphore does not exist.
' (2) The semaphore exists, but the current user doesn't
' have access. (3) The semaphore exists and the user has
' access.
'
If doesNotExist Then
' The semaphore does not exist, so create it.
'
' The value of this variable is set by the semaphore
' constructor. It is True if the named system semaphore was
' created, and False if the named semaphore already existed.
'
Dim semaphoreWasCreated As Boolean
' Create an access control list (ACL) that denies the
' current user the right to enter or release the
' semaphore, but allows the right to read and change
' security information for the semaphore.
'
Dim user As String = Environment.UserDomainName _
& "\" & Environment.UserName
Dim semSec As New SemaphoreSecurity()
Dim rule As New SemaphoreAccessRule(user, _
SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
AccessControlType.Deny)
semSec.AddAccessRule(rule)
rule = New SemaphoreAccessRule(user, _
SemaphoreRights.ReadPermissions Or _
SemaphoreRights.ChangePermissions, _
AccessControlType.Allow)
semSec.AddAccessRule(rule)
' Create a Semaphore object that represents the system
' semaphore named by the constant 'semaphoreName', with
' maximum count three, initial count three, and the
' specified security access. The Boolean value that
' indicates creation of the underlying system object is
' placed in semaphoreWasCreated.
'
sem = New Semaphore(3, 3, semaphoreName, _
semaphoreWasCreated, semSec)
' If the named system semaphore was created, it can be
' used by the current instance of this program, even
' though the current user is denied access. The current
' program enters the semaphore. Otherwise, exit the
' program.
'
If semaphoreWasCreated Then
Console.WriteLine("Created the semaphore.")
Else
Console.WriteLine("Unable to create the semaphore.")
Return
End If
ElseIf unauthorized Then
' Open the semaphore to read and change the access
' control security. The access control security defined
' above allows the current user to do this.
'
Try
sem = Semaphore.OpenExisting(semaphoreName, _
SemaphoreRights.ReadPermissions Or _
SemaphoreRights.ChangePermissions)
' Get the current ACL. This requires
' SemaphoreRights.ReadPermissions.
Dim semSec As SemaphoreSecurity = sem.GetAccessControl()
Dim user As String = Environment.UserDomainName _
& "\" & Environment.UserName
' First, the rule that denied the current user
' the right to enter and release the semaphore must
' be removed.
Dim rule As New SemaphoreAccessRule(user, _
SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
AccessControlType.Deny)
semSec.RemoveAccessRule(rule)
' Now grant the user the correct rights.
'
rule = New SemaphoreAccessRule(user, _
SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
AccessControlType.Allow)
semSec.AddAccessRule(rule)
' Update the ACL. This requires
' SemaphoreRights.ChangePermissions.
sem.SetAccessControl(semSec)
Console.WriteLine("Updated semaphore security.")
' Open the semaphore with (SemaphoreRights.Synchronize
' Or SemaphoreRights.Modify), the rights required to
' enter and release the semaphore.
'
sem = Semaphore.OpenExisting(semaphoreName)
Catch ex As UnauthorizedAccessException
Console.WriteLine("Unable to change permissions: {0}", _
ex.Message)
Return
End Try
End If
' Enter the semaphore, and hold it until the program
' exits.
'
Try
sem.WaitOne()
Console.WriteLine("Entered the semaphore.")
Console.WriteLine("Press the Enter key to exit.")
Console.ReadLine()
sem.Release()
Catch ex As UnauthorizedAccessException
Console.WriteLine("Unauthorized access: {0}", _
ex.Message)
End Try
End Sub
End Class
Commenti
Può name essere preceduto Global\ da o Local\ per specificare uno spazio dei nomi. Quando si specifica lo Global spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con qualsiasi processo nel sistema. Quando si specifica lo Local spazio dei nomi , che è anche l'impostazione predefinita quando non viene specificato alcuno spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con i processi nella stessa sessione. In Windows una sessione è una sessione di accesso e i servizi vengono in genere eseguiti in una sessione non interattiva diversa. Nei sistemi operativi simili a Unix, ogni shell ha una propria sessione. Gli oggetti di sincronizzazione locale della sessione possono essere appropriati per la sincronizzazione tra processi con una relazione padre/figlio in cui vengono eseguiti tutti nella stessa sessione. Per altre informazioni sui nomi degli oggetti di sincronizzazione in Windows, vedere Nomina oggetto.
Se esiste un oggetto di sincronizzazione del tipo richiesto nello spazio dei nomi , viene aperto l'oggetto di sincronizzazione esistente. Se non esiste un oggetto di sincronizzazione nello spazio dei nomi o un oggetto di sincronizzazione di un tipo diverso esiste nello spazio dei nomi , viene generato un oggetto WaitHandleCannotBeOpenedException .
Il rights parametro deve includere il SemaphoreRights.Synchronize flag per consentire ai thread di immettere il semaforo e il SemaphoreRights.Modify flag per consentire ai thread di chiamare il Release metodo .
Il OpenExisting metodo tenta di aprire un semaforo denominato esistente. Per creare il semaforo di sistema quando non esiste già, usare uno dei Semaphore costruttori con un name parametro .
Più chiamate a questo metodo che utilizzano lo stesso valore per name non restituiscono necessariamente lo stesso Semaphore oggetto, anche se gli oggetti restituiti rappresentano lo stesso semaforo di sistema denominato.
Vedi anche
- di threading gestito
- Semaforo
Si applica a
OpenExisting(String, NamedWaitHandleOptions)
- Origine:
- Semaphore.cs
- Origine:
- Semaphore.cs
Apre il semaforo denominato specificato, se già esistente. Se le opzioni sono impostate solo sull'utente corrente, i controlli di accesso dell'oggetto vengono verificati per l'utente chiamante.
public:
static System::Threading::Semaphore ^ OpenExisting(System::String ^ name, System::Threading::NamedWaitHandleOptions options);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static System.Threading.Semaphore OpenExisting(string name, System.Threading.NamedWaitHandleOptions options);
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
static member OpenExisting : string * System.Threading.NamedWaitHandleOptions -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String, options As NamedWaitHandleOptions) As Semaphore
Parametri
- name
- String
Nome dell'oggetto di sincronizzazione da condividere con altri processi. Il nome fa distinzione tra maiuscole e minuscole. Il carattere barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni.
- options
- NamedWaitHandleOptions
Opzioni di ambito per il semaforo denominato. Per impostazione predefinita, l'accesso è limitato solo all'utente corrente e alla sessione corrente. Le opzioni specificate potrebbero influire sullo spazio dei nomi per il nome e l'accesso all'oggetto semaforo sottostante.
Valori restituiti
Oggetto che rappresenta il semaforo di sistema denominato.
- Attributi
Eccezioni
name è una stringa vuota.
name è null.
Impossibile creare un oggetto di sincronizzazione con l'oggetto specificato name . Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome.
oppure
Esiste un oggetto con l'oggetto specificato, ma l'oggetto specificato nameoptions non è compatibile con le opzioni dell'oggetto esistente.
name non è valido. Questo può essere per vari motivi, incluse alcune restrizioni che potrebbero essere inserite dal sistema operativo, ad esempio un prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" fanno distinzione tra maiuscole e minuscole.
oppure
Si è verificato un altro errore. La HResult proprietà potrebbe fornire altre informazioni.
name supera la lunghezza consentita. Le restrizioni relative alla lunghezza possono dipendere dal sistema operativo o dalla configurazione.
Il semaforo denominato esiste, ma l'utente non ha l'accesso di sicurezza necessario per usarlo.
Commenti
Se esiste un oggetto di sincronizzazione del tipo richiesto nello spazio dei nomi , viene aperto l'oggetto di sincronizzazione esistente. Tuttavia, se options specifica l'accesso limitato all'utente corrente e l'oggetto di sincronizzazione non è compatibile con esso, viene generata un'eccezione WaitHandleCannotBeOpenedException . Se non esiste un oggetto di sincronizzazione nello spazio dei nomi o un oggetto di sincronizzazione di un tipo diverso esiste nello spazio dei nomi , viene generata anche un'eccezione WaitHandleCannotBeOpenedException .
Il OpenExisting metodo tenta di aprire il semaforo denominato specificato. Per creare il semaforo di sistema quando non esiste già, usare uno dei Semaphore costruttori con un name parametro .
Più chiamate a questo metodo che utilizzano lo stesso valore per name non restituiscono necessariamente lo stesso Semaphore oggetto, anche se gli oggetti restituiti rappresentano lo stesso semaforo di sistema denominato.
Vedi anche
- di threading gestito
- Semaforo