Semaphore.OpenExisting 方法

定义

打开指定的命名信号灯(如果已存在)。

重载

名称 说明
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框架:name的长度超过MAX_PATH(260 个字符)。

namenull

无法创建具有提供的 name 同步对象。 不同类型的同步对象可能具有相同的名称。 在某些情况下,可能会为无效名称引发此异常。

name 无效。 这可能是出于各种原因,包括操作系统可能放置的一些限制,例如未知前缀或无效字符。 请注意,名称和通用前缀“Global\”和“Local\”区分大小写。

-或-

还有其他一些错误。 该 HResult 属性可能提供更多信息。

name 太长。 长度限制可能取决于操作系统或配置。

命名信号灯存在,但用户没有使用它所需的安全访问权限。

示例

下面的代码示例演示具有访问控制安全性的命名信号灯的跨进程行为。 该示例使用 OpenExisting(String) 方法重载测试命名信号灯是否存在。

如果信号灯不存在,则创建信号灯的最大计数为 2,访问控制安全性可拒绝当前用户使用信号灯的权限,但授予对信号灯的读取和更改权限的权限。

如果从两个命令窗口运行编译的示例,则第二个副本会在调用 OpenExisting(String) 方法重载时引发访问冲突异常。 捕获异常,该示例使用 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 的操作系统上,每个 shell 都有自己的会话。 会话本地同步对象可能适合在进程与父/子关系之间同步,其中它们都在同一会话中运行。 有关Windows上的同步对象名称的详细信息,请参阅 Object Names

如果命名空间中存在所请求类型的同步对象,则会打开现有同步对象。 如果命名空间中不存在同步对象,或者命名空间中存在不同类型的同步对象,则会引发一个 WaitHandleCannotBeOpenedException

该方法 OpenExisting 尝试打开指定的命名信号灯。 若要在系统信号灯尚不存在时创建系统信号灯,请使用具有参数的构造函数之 Semaphorename

对此方法使用相同值的 name 多次调用不一定返回相同的 Semaphore 对象,即使返回的对象表示同一命名的系统信号灯。

此方法重载等效于使用按位 OR 操作调用 OpenExisting 方法重载和指定 SemaphoreRights.SynchronizeSemaphoreRights.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框架:name的长度超过MAX_PATH(260 个字符)。

namenull

无法创建具有提供的 name 同步对象。 不同类型的同步对象可能具有相同的名称。 在某些情况下,可能会为无效名称引发此异常。

name 无效。 这可能是出于各种原因,包括操作系统可能放置的一些限制,例如未知前缀或无效字符。 请注意,名称和通用前缀“Global\”和“Local\”区分大小写。

-或-

还有其他一些错误。 该 HResult 属性可能提供更多信息。

name 太长。 长度限制可能取决于操作系统或配置。

命名信号灯存在,但用户没有所需的安全访问权限。

示例

下面的代码示例演示具有访问控制安全性的命名信号灯的跨进程行为。 该示例使用 OpenExisting(String) 方法重载测试命名信号灯是否存在。

如果信号灯不存在,则创建信号灯的最大计数为 2,访问控制安全性可拒绝当前用户使用信号灯的权限,但授予对信号灯的读取和更改权限的权限。

如果从两个命令窗口运行编译的示例,则第二个副本将在调用 OpenExisting(String) 该方法时引发访问冲突异常。 捕获异常,该示例使用 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 的操作系统上,每个 shell 都有自己的会话。 会话本地同步对象可能适合在进程与父/子关系之间同步,其中它们都在同一会话中运行。 有关Windows上的同步对象名称的详细信息,请参阅 Object Names

如果命名空间中存在所请求类型的同步对象,则会打开现有同步对象。 如果命名空间中不存在同步对象,或者命名空间中存在不同类型的同步对象,则会引发一个 WaitHandleCannotBeOpenedException

参数 rights 必须包含 SemaphoreRights.Synchronize 标志,以允许线程输入信号灯,以及 SemaphoreRights.Modify 允许线程调用该方法的 Release 标志。

该方法 OpenExisting 尝试打开现有的命名信号灯。 若要在系统信号灯尚不存在时创建系统信号灯,请使用具有参数的构造函数之 Semaphorename

对此方法使用相同值的 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 指定对当前用户的访问权限,并且同步对象与它不兼容,则会引发一个 WaitHandleCannotBeOpenedException 。 如果命名空间中不存在同步对象,或者命名空间中也存在不同类型的同步对象,也会引发一个 WaitHandleCannotBeOpenedException 同步对象。

该方法 OpenExisting 尝试打开指定的命名信号灯。 若要在系统信号灯尚不存在时创建系统信号灯,请使用具有参数的构造函数之 Semaphorename

对此方法使用相同值的 name 多次调用不一定返回相同的 Semaphore 对象,即使返回的对象表示同一命名的系统信号灯。

另请参阅

适用于