Semaphore.OpenExisting 메서드

정의

이미 있는 경우 지정된 명명된 세마포를 엽니다.

오버로드

Name Description
OpenExisting(String)

이미 있는 경우 지정된 명명된 세마포를 엽니다.

OpenExisting(String, SemaphoreRights)

지정된 명명된 세마포가 이미 있는 경우 원하는 보안 액세스를 사용하여 엽니다.

OpenExisting(String, NamedWaitHandleOptions)

이미 있는 경우 지정된 명명된 세마포를 엽니다. 옵션이 현재 사용자로만 설정된 경우 호출하는 사용자에 대해 개체의 액세스 제어가 확인됩니다.

OpenExisting(String)

Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs

이미 있는 경우 지정된 명명된 세마포를 엽니다.

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

매개 변수

name
String

다른 프로세스와 공유할 동기화 개체의 이름입니다. 이름은 대/소문자를 구분합니다. 백슬래시 문자(\)는 예약되어 있으며 네임스페이스를 지정하는 데만 사용할 수 있습니다. 네임스페이스에 대한 자세한 내용은 설명 섹션을 참조하세요. 운영 체제에 따라 이름에 대한 추가 제한 사항이 있을 수 있습니다. 예를 들어 Unix 기반 운영 체제에서 네임스페이스를 제외한 후의 이름은 유효한 파일 이름이어야 합니다.

반품

명명된 시스템 세마포를 나타내는 개체입니다.

특성

예외

name 은 빈 문자열입니다.

-또는-

.NET Framework만 해당: name MAX_PATH(260자)보다 깁니다.

namenull입니다.

제공된 name 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체의 이름은 같을 수 있습니다. 경우에 따라 잘못된 이름에 대해 이 예외가 throw될 수 있습니다.

name 가 잘못되었습니다. 이는 알 수 없는 접두사 또는 잘못된 문자와 같이 운영 체제에서 적용할 수 있는 몇 가지 제한을 포함하여 다양한 이유로 발생할 수 있습니다. 이름 및 일반 접두사 "Global\" 및 "Local\"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. 이 속성은 HResult 자세한 정보를 제공할 수 있습니다.

name이 너무 깁니다. 길이 제한은 운영 체제 또는 구성에 따라 달라질 수 있습니다.

명명된 세마포가 있지만 사용자에게는 이 세마포를 사용하는 데 필요한 보안 액세스 권한이 없습니다.

예제

다음 코드 예제에서는 액세스 제어 보안을 사용하여 명명된 세마포의 교차 프로세스 동작을 보여 줍니다. 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String) 명명된 세마포가 있는지 테스트합니다.

세마포가 없으면 현재 사용자에게 세마포를 사용할 수 있는 권한을 거부하지만 세마포에 대한 읽기 및 변경 권한을 부여하는 액세스 제어 보안과 함께 최대 2개의 개수로 생성됩니다.

두 명령 창에서 컴파일된 예제를 실행하는 경우 두 번째 복사본은 메서드 오버로드 호출에 대한 액세스 위반 예외를 OpenExisting(String) throw합니다. 예외가 catch되고, 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String, SemaphoreRights) 사용 권한을 읽고 변경하는 데 필요한 권한으로 세마포를 엽니다.

사용 권한이 변경되면 세마포를 입력하고 해제하는 데 필요한 권한으로 열립니다. 세 번째 명령 창에서 컴파일된 예제를 실행하면 새 사용 권한을 사용하여 실행됩니다.

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

설명

name 네임스페이스를 접두사로 Global\ 지정하거나 Local\ 지정할 수 있습니다. Global 네임스페이스를 지정하면 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다. Local 네임스페이스가 지정되지 않은 경우에도 기본값인 네임스페이스를 지정하면 동기화 개체를 동일한 세션의 프로세스와 공유할 수 있습니다. Windows 세션은 로그인 세션이며 서비스는 일반적으로 다른 비대화형 세션에서 실행됩니다. Unix와 유사한 운영 체제에서 각 셸에는 자체 세션이 있습니다. 세션-로컬 동기화 개체는 모두 동일한 세션에서 실행되는 부모/자식 관계와 프로세스 간의 동기화에 적합할 수 있습니다. Windows 동기화 개체 이름에 대한 자세한 내용은 Object Names 참조하세요.

요청된 형식의 동기화 개체가 네임스페이스에 있으면 기존 동기화 개체가 열립니다. 동기화 개체가 네임스페이스에 없거나 다른 형식의 동기화 개체가 네임스페이스에 있으면 throw WaitHandleCannotBeOpenedException 됩니다.

메서드는 OpenExisting 지정된 명명된 세마포를 열려고 시도합니다. 시스템 세마포가 아직 없는 경우 만들려면 매개 변수가 Semaphore 있는 name 생성자 중 하나를 사용합니다.

반환되는 개체가 동일한 명명된 시스템 세마포를 나타내더라도 동일한 값을 사용하는 이 메서드에 대한 name 여러 호출이 반드시 동일한 Semaphore 개체를 반환하지는 않습니다.

이 메서드 오버로드는 메서드 오버로드를 호출 OpenExisting 하고 비트 OR 연산을 SemaphoreRights.Synchronize 사용하여 결합된 지정 및 권한과 SemaphoreRights.Modify 동일합니다.

플래그를 SemaphoreRights.Synchronize 지정하면 스레드가 세마포에 들어갈 수 있으며 플래그를 SemaphoreRights.Modify 지정하면 스레드가 메서드를 호출 Release 할 수 있습니다.

추가 정보

적용 대상

OpenExisting(String, SemaphoreRights)

지정된 명명된 세마포가 이미 있는 경우 원하는 보안 액세스를 사용하여 엽니다.

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

매개 변수

name
String

다른 프로세스와 공유할 동기화 개체의 이름입니다. 이름은 대/소문자를 구분합니다. 백슬래시 문자(\)는 예약되어 있으며 네임스페이스를 지정하는 데만 사용할 수 있습니다. 네임스페이스에 대한 자세한 내용은 설명 섹션을 참조하세요. 운영 체제에 따라 이름에 대한 추가 제한 사항이 있을 수 있습니다. 예를 들어 Unix 기반 운영 체제에서 네임스페이스를 제외한 후의 이름은 유효한 파일 이름이어야 합니다.

rights
SemaphoreRights

원하는 보안 액세스를 나타내는 열거형 값의 비트 조합입니다.

반품

명명된 시스템 세마포를 나타내는 개체입니다.

예외

name 은 빈 문자열입니다.

-또는-

.NET Framework만 해당: name MAX_PATH(260자)보다 깁니다.

namenull입니다.

제공된 name 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체의 이름은 같을 수 있습니다. 경우에 따라 잘못된 이름에 대해 이 예외가 throw될 수 있습니다.

name 가 잘못되었습니다. 이는 알 수 없는 접두사 또는 잘못된 문자와 같이 운영 체제에서 적용할 수 있는 몇 가지 제한을 포함하여 다양한 이유로 발생할 수 있습니다. 이름 및 일반 접두사 "Global\" 및 "Local\"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. 이 속성은 HResult 자세한 정보를 제공할 수 있습니다.

name이 너무 깁니다. 길이 제한은 운영 체제 또는 구성에 따라 달라질 수 있습니다.

명명된 세마포가 있지만 사용자에게 원하는 보안 액세스 권한이 없습니다.

예제

다음 코드 예제에서는 액세스 제어 보안을 사용하여 명명된 세마포의 교차 프로세스 동작을 보여 줍니다. 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String) 명명된 세마포가 있는지 테스트합니다.

세마포가 없으면 현재 사용자에게 세마포를 사용할 수 있는 권한을 거부하지만 세마포에 대한 읽기 및 변경 권한을 부여하는 액세스 제어 보안과 함께 최대 2개의 개수로 생성됩니다.

두 명령 창에서 컴파일된 예제를 실행하는 경우 두 번째 복사본은 메서드 호출에서 액세스 위반 예외를 OpenExisting(String) throw합니다. 예외가 catch되고, 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String, SemaphoreRights) 사용 권한을 읽고 변경하는 데 필요한 권한으로 세마포를 엽니다.

사용 권한이 변경되면 세마포를 입력하고 해제하는 데 필요한 권한으로 열립니다. 세 번째 명령 창에서 컴파일된 예제를 실행하면 새 사용 권한을 사용하여 실행됩니다.

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

설명

name 네임스페이스를 접두사로 Global\ 지정하거나 Local\ 지정할 수 있습니다. Global 네임스페이스를 지정하면 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다. Local 네임스페이스가 지정되지 않은 경우에도 기본값인 네임스페이스를 지정하면 동기화 개체를 동일한 세션의 프로세스와 공유할 수 있습니다. Windows 세션은 로그인 세션이며 서비스는 일반적으로 다른 비대화형 세션에서 실행됩니다. Unix와 유사한 운영 체제에서 각 셸에는 자체 세션이 있습니다. 세션-로컬 동기화 개체는 모두 동일한 세션에서 실행되는 부모/자식 관계와 프로세스 간의 동기화에 적합할 수 있습니다. Windows 동기화 개체 이름에 대한 자세한 내용은 Object Names 참조하세요.

요청된 형식의 동기화 개체가 네임스페이스에 있으면 기존 동기화 개체가 열립니다. 동기화 개체가 네임스페이스에 없거나 다른 형식의 동기화 개체가 네임스페이스에 있으면 throw WaitHandleCannotBeOpenedException 됩니다.

매개 변수에는 rights 스레드가 SemaphoreRights.Synchronize 세마포를 입력할 수 있도록 하는 플래그와 스레드가 SemaphoreRights.Modify 메서드를 호출할 수 있도록 하는 플래그가 Release 포함되어야 합니다.

메서드는 OpenExisting 기존의 명명된 세마포를 열려고 합니다. 시스템 세마포가 아직 없는 경우 만들려면 매개 변수가 Semaphore 있는 name 생성자 중 하나를 사용합니다.

반환되는 개체가 동일한 명명된 시스템 세마포를 나타내더라도 동일한 값을 사용하는 이 메서드에 대한 name 여러 호출이 반드시 동일한 Semaphore 개체를 반환하지는 않습니다.

추가 정보

적용 대상

OpenExisting(String, NamedWaitHandleOptions)

Source:
Semaphore.cs
Source:
Semaphore.cs

이미 있는 경우 지정된 명명된 세마포를 엽니다. 옵션이 현재 사용자로만 설정된 경우 호출하는 사용자에 대해 개체의 액세스 제어가 확인됩니다.

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

매개 변수

name
String

다른 프로세스와 공유할 동기화 개체의 이름입니다. 이름은 대/소문자를 구분합니다. 백슬래시 문자(\)는 예약되어 있으며 네임스페이스를 지정하는 데만 사용할 수 있습니다. 네임스페이스에 대한 자세한 내용은 설명 섹션을 참조하세요.

options
NamedWaitHandleOptions

명명된 세마포에 대한 범위 옵션입니다. 기본값은 현재 사용자 및 현재 세션으로만 제한됩니다. 지정된 옵션은 이름 및 기본 세마포 개체에 대한 액세스의 네임스페이스에 영향을 줄 수 있습니다.

반품

명명된 시스템 세마포를 나타내는 개체입니다.

특성

예외

name 은 빈 문자열입니다.

namenull입니다.

제공된 name 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체의 이름은 같을 수 있습니다.

-또는-

지정된 name 개체가 있지만 지정된 options 개체가 기존 개체의 옵션과 호환되지 않습니다.

name 가 잘못되었습니다. 이는 알 수 없는 접두사 또는 잘못된 문자와 같이 운영 체제에서 적용할 수 있는 몇 가지 제한을 포함하여 다양한 이유로 발생할 수 있습니다. 이름 및 일반 접두사 "Global\" 및 "Local\"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. 이 속성은 HResult 자세한 정보를 제공할 수 있습니다.

name이 너무 깁니다. 길이 제한은 운영 체제 또는 구성에 따라 달라질 수 있습니다.

명명된 세마포가 있지만 사용자에게는 이 세마포를 사용하는 데 필요한 보안 액세스 권한이 없습니다.

설명

요청된 형식의 동기화 개체가 네임스페이스에 있으면 기존 동기화 개체가 열립니다. 그러나 현재 사용자로 제한된 액세스를 지정하고 동기화 개체가 해당 사용자와 호환되지 않는 경우 options throw WaitHandleCannotBeOpenedException 됩니다. 네임스페이스에 동기화 개체가 없거나 다른 형식의 동기화 개체가 네임스페이스에 있으면 해당 개체 WaitHandleCannotBeOpenedException 도 throw됩니다.

메서드는 OpenExisting 지정된 명명된 세마포를 열려고 시도합니다. 시스템 세마포가 아직 없는 경우 만들려면 매개 변수가 Semaphore 있는 name 생성자 중 하나를 사용합니다.

반환되는 개체가 동일한 명명된 시스템 세마포를 나타내더라도 동일한 값을 사용하는 이 메서드에 대한 name 여러 호출이 반드시 동일한 Semaphore 개체를 반환하지는 않습니다.

추가 정보

적용 대상