Semaphore 构造函数

定义

初始化 Semaphore 类的新实例。Initializes a new instance of the Semaphore class.

重载

Semaphore(Int32, Int32)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries.

Semaphore(Int32, Int32, String)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数,可以选择指定系统信号量对象的名称。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, and optionally specifying the name of a system semaphore object.

Semaphore(Int32, Int32, String, Boolean)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数,还可以选择指定系统信号量对象的名称,以及指定一个变量来接收指示是否创建了新系统信号量的值。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, and specifying a variable that receives a value indicating whether a new system semaphore was created.

Semaphore(Int32, Int32, String, Boolean, SemaphoreSecurity)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数,可以选择指定系统信号量对象的名称,指定一个变量来接收指示是否创建了新系统信号量的值,以及指定系统信号量的安全访问控制。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, specifying a variable that receives a value indicating whether a new system semaphore was created, and specifying security access control for the system semaphore.

Semaphore(Int32, Int32)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries.

public:
 Semaphore(int initialCount, int maximumCount);
public Semaphore (int initialCount, int maximumCount);
new System.Threading.Semaphore : int * int -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer)

参数

initialCount
Int32

可以同时授予的信号量的初始请求数。The initial number of requests for the semaphore that can be granted concurrently.

maximumCount
Int32

可以同时授予的信号量的最大请求数。The maximum number of requests for the semaphore that can be granted concurrently.

异常

initialCount 大于 maximumCountinitialCount is greater than maximumCount.

maximumCount 小于 1。maximumCount is less than 1.

- 或 --or- initialCount 小于 0。initialCount is less than 0.

示例

下面的示例创建一个信号量,其最大计数为3,初始计数为零。The following example creates a semaphore with a maximum count of three and an initial count of zero. 该示例启动五个线程,这会阻止等待信号量。The example starts five threads, which block waiting for the semaphore. 主线程使用 Release(Int32) 方法重载将信号量计数增加到其最大值,从而允许三个线程进入信号量。The main thread uses the Release(Int32) method overload to increase the semaphore count to its maximum, allowing three threads to enter the semaphore. 每个线程使用 Thread.Sleep 方法来等待一秒,模拟工作,然后调用 Release() 方法重载以释放信号量。Each thread uses the Thread.Sleep method to wait for one second, to simulate work, and then calls the Release() method overload to release the semaphore. 每次释放信号灯时,都将显示以前的信号量计数。Each time the semaphore is released, the previous semaphore count is displayed. 控制台消息跟踪信号量使用。Console messages track semaphore use. 每个线程的模拟工作时间间隔略有增加,使输出更易于读取。The simulated work interval is increased slightly for each thread, to make the output easier to read.

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // A semaphore that simulates a limited resource pool.
   //
   static Semaphore^ _pool;

   // A padding interval to make the output more orderly.
   static int _padding;

public:
   static void Main()
   {
      // Create a semaphore that can satisfy up to three
      // concurrent requests. Use an initial count of zero,
      // so that the entire semaphore count is initially
      // owned by the main program thread.
      //
      _pool = gcnew Semaphore( 0,3 );
      
      // Create and start five numbered threads.
      //
      for ( int i = 1; i <= 5; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( Worker ) );
         
         // Start the thread, passing the number.
         //
         t->Start( i );
      }
      
      // Wait for half a second, to allow all the
      // threads to start and to block on the semaphore.
      //
      Thread::Sleep( 500 );
      
      // The main thread starts out holding the entire
      // semaphore count. Calling Release(3) brings the
      // semaphore count back to its maximum value, and
      // allows the waiting threads to enter the semaphore,
      // up to three at a time.
      //
      Console::WriteLine( L"Main thread calls Release(3)." );
      _pool->Release( 3 );

      Console::WriteLine( L"Main thread exits." );
   }

private:
   static void Worker( Object^ num )
   {
      // Each worker thread begins by requesting the
      // semaphore.
      Console::WriteLine( L"Thread {0} begins and waits for the semaphore.", num );
      _pool->WaitOne();
      
      // A padding interval to make the output more orderly.
      int padding = Interlocked::Add( _padding, 100 );

      Console::WriteLine( L"Thread {0} enters the semaphore.", num );
      
      // The thread's "work" consists of sleeping for
      // about a second. Each thread "works" a little
      // longer, just to make the output more orderly.
      //
      Thread::Sleep( 1000 + padding );

      Console::WriteLine( L"Thread {0} releases the semaphore.", num );
      Console::WriteLine( L"Thread {0} previous semaphore count: {1}",
         num, _pool->Release() );
   }
};
using System;
using System.Threading;

public class Example
{
    // A semaphore that simulates a limited resource pool.
    //
    private static Semaphore _pool;

    // A padding interval to make the output more orderly.
    private static int _padding;

    public static void Main()
    {
        // Create a semaphore that can satisfy up to three
        // concurrent requests. Use an initial count of zero,
        // so that the entire semaphore count is initially
        // owned by the main program thread.
        //
        _pool = new Semaphore(0, 3);

        // Create and start five numbered threads. 
        //
        for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));

            // Start the thread, passing the number.
            //
            t.Start(i);
        }

        // Wait for half a second, to allow all the
        // threads to start and to block on the semaphore.
        //
        Thread.Sleep(500);

        // The main thread starts out holding the entire
        // semaphore count. Calling Release(3) brings the 
        // semaphore count back to its maximum value, and
        // allows the waiting threads to enter the semaphore,
        // up to three at a time.
        //
        Console.WriteLine("Main thread calls Release(3).");
        _pool.Release(3);

        Console.WriteLine("Main thread exits.");
    }

    private static void Worker(object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins " +
            "and waits for the semaphore.", num);
        _pool.WaitOne();

        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(ref _padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        
        // The thread's "work" consists of sleeping for 
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly.
        //
        Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
}
Imports System.Threading

Public Class Example

    ' A semaphore that simulates a limited resource pool.
    '
    Private Shared _pool As Semaphore

    ' A padding interval to make the output more orderly.
    Private Shared _padding As Integer

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a semaphore that can satisfy up to three
        ' concurrent requests. Use an initial count of zero,
        ' so that the entire semaphore count is initially
        ' owned by the main program thread.
        '
        _pool = New Semaphore(0, 3)

        ' Create and start five numbered threads. 
        '
        For i As Integer = 1 To 5
            Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker))
            'Dim t As New Thread(AddressOf Worker)

            ' Start the thread, passing the number.
            '
            t.Start(i)
        Next i

        ' Wait for half a second, to allow all the
        ' threads to start and to block on the semaphore.
        '
        Thread.Sleep(500)

        ' The main thread starts out holding the entire
        ' semaphore count. Calling Release(3) brings the 
        ' semaphore count back to its maximum value, and
        ' allows the waiting threads to enter the semaphore,
        ' up to three at a time.
        '
        Console.WriteLine("Main thread calls Release(3).")
        _pool.Release(3)

        Console.WriteLine("Main thread exits.")
    End Sub

    Private Shared Sub Worker(ByVal num As Object)
        ' Each worker thread begins by requesting the
        ' semaphore.
        Console.WriteLine("Thread {0} begins " _
            & "and waits for the semaphore.", num)
        _pool.WaitOne()

        ' A padding interval to make the output more orderly.
        Dim padding As Integer = Interlocked.Add(_padding, 100)

        Console.WriteLine("Thread {0} enters the semaphore.", num)
        
        ' The thread's "work" consists of sleeping for 
        ' about a second. Each thread "works" a little 
        ' longer, just to make the output more orderly.
        '
        Thread.Sleep(1000 + padding)

        Console.WriteLine("Thread {0} releases the semaphore.", num)
        Console.WriteLine("Thread {0} previous semaphore count: {1}", _
            num, _
            _pool.Release())
    End Sub
End Class

注解

此构造函数初始化未命名的信号量。This constructor initializes an unnamed semaphore. 使用此类信号量的实例的所有线程都必须具有对该实例的引用。All threads that use an instance of such a semaphore must have references to the instance.

如果 initialCount 小于 maximumCount,则其效果与当前线程已调用 WaitOnemaximumCountinitialCount)次相同。If initialCount is less than maximumCount, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. 如果你不希望为创建信号量的线程保留任何条目,请对 maximumCountinitialCount使用相同的数字。If you do not want to reserve any entries for the thread that creates the semaphore, use the same number for maximumCount and initialCount.

另请参阅

Semaphore(Int32, Int32, String)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数,可以选择指定系统信号量对象的名称。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, and optionally specifying the name of a system semaphore object.

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name);
public Semaphore (int initialCount, int maximumCount, string name);
new System.Threading.Semaphore : int * int * string -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String)

参数

initialCount
Int32

可以同时授予的信号量的初始请求数。The initial number of requests for the semaphore that can be granted concurrently.

maximumCount
Int32

可以同时授予的信号量的最大请求数。The maximum number of requests for the semaphore that can be granted concurrently.

name
String

命名系统信号量对象的名称。The name of a named system semaphore object.

异常

initialCount 大于 maximumCountinitialCount is greater than maximumCount.

- 或 --or- name 超过 260 个字符。name is longer than 260 characters.

maximumCount 小于 1。maximumCount is less than 1.

- 或 --or- initialCount 小于 0。initialCount is less than 0.

出现 Win32 错误。A Win32 error occurred.

命名信号量存在且具有访问控制安全性,用户不具有 FullControlThe named semaphore exists and has access control security, and the user does not have FullControl.

无法创建命名信号量,可能是由于其他类型的等待句柄具有相同名称。The named semaphore cannot be created, perhaps because a wait handle of a different type has the same name.

示例

下面的代码示例演示命名信号量的跨进程行为。The following code example demonstrates the cross-process behavior of a named semaphore. 该示例创建一个名为的信号量,其最大计数为5,初始计数为5。The example creates a named semaphore with a maximum count of five and an initial count of five. 该程序对 WaitOne 方法进行了三次调用。The program makes three calls to the WaitOne method. 因此,如果从两个命令窗口运行已编译的示例,第二个副本会阻止第三次调用 WaitOneThus, if you run the compiled example from two command windows, the second copy will block on the third call to WaitOne. 释放程序的第一个副本中的一个或多个项以解除阻止第二个副本。Release one or more entries in the first copy of the program to unblock the second.

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // Create a Semaphore object that represents the named
      // system semaphore "SemaphoreExample3". The semaphore has a
      // maximum count of five. The initial count is also five.
      // There is no point in using a smaller initial count,
      // because the initial count is not used if this program
      // doesn't create the named system semaphore, and with
      // this method overload there is no way to tell. Thus, this
      // program assumes that it is competing with other
      // programs for the semaphore.
      //
      Semaphore^ sem = gcnew Semaphore( 5,5,L"SemaphoreExample3" );
      
      // Attempt to enter the semaphore three times. If another
      // copy of this program is already running, only the first
      // two requests can be satisfied. The third blocks. Note
      // that in a real application, timeouts should be used
      // on the WaitOne calls, to avoid deadlocks.
      //
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore once." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore twice." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore three times." );
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release." );
      int n;
      if ( Int32::TryParse( Console::ReadLine(),n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample3". The semaphore has a
        // maximum count of five. The initial count is also five. 
        // There is no point in using a smaller initial count,
        // because the initial count is not used if this program
        // doesn't create the named system semaphore, and with 
        // this method overload there is no way to tell. Thus, this
        // program assumes that it is competing with other
        // programs for the semaphore.
        //
        Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3");

        // Attempt to enter the semaphore three times. If another 
        // copy of this program is already running, only the first
        // two requests can be satisfied. The third blocks. Note 
        // that in a real application, timeouts should be used
        // on the WaitOne calls, to avoid deadlocks.
        //
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore once.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore twice.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore three times.");

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    }
}
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample3". The semaphore has a
        ' maximum count of five. The initial count is also five. 
        ' There is no point in using a smaller initial count,
        ' because the initial count is not used if this program
        ' doesn't create the named system semaphore, and with 
        ' this method overload there is no way to tell. Thus, this
        ' program assumes that it is competing with other
        ' programs for the semaphore.
        '
        Dim sem As New Semaphore(5, 5, "SemaphoreExample3")

        ' Attempt to enter the semaphore three times. If another 
        ' copy of this program is already running, only the first
        ' two requests can be satisfied. The third blocks. Note 
        ' that in a real application, timeouts should be used
        ' on the WaitOne calls, to avoid deadlocks.
        '
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore once.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore twice.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore three times.")

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(), n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining " _
                & "count ({0}) and exit the program.", remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class 

注解

此构造函数初始化表示已命名的系统信号量的 Semaphore 对象。This constructor initializes a Semaphore object that represents a named system semaphore. 可以创建多个表示同一命名系统信号量的 Semaphore 对象。You can create multiple Semaphore objects that represent the same named system semaphore.

如果已命名的系统信号量不存在,则使用 initialCountmaximumCount指定的初始计数和最大计数来创建它。If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 如果已命名的系统信号量已存在,则不会使用 initialCountmaximumCount,尽管无效值仍然会导致异常。If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. 如果需要确定是否创建了已命名的系统信号量,请改用 Semaphore(Int32, Int32, String, Boolean) 构造函数重载。If you need to determine whether or not a named system semaphore was created, use the Semaphore(Int32, Int32, String, Boolean) constructor overload instead.

重要

使用此构造函数重载时,建议的做法是为 initialCountmaximumCount指定相同的数字。When you use this constructor overload, the recommended practice is to specify the same number for initialCount and maximumCount. 如果 initialCount 小于 maximumCount,并且创建了已命名的系统信号量,则其效果与当前线程已调用 WaitOnemaximumCountinitialCount)次的效果相同。If initialCount is less than maximumCount, and a named system semaphore is created, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. 但是,使用此构造函数重载无法确定是否创建了已命名的系统信号量。However, with this constructor overload there is no way to determine whether a named system semaphore was created.

如果为 name指定 null 或空字符串,则将创建一个本地信号量,就像您已经调用了 Semaphore(Int32, Int32) 构造函数重载一样。If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload.

因为命名的信号量在整个操作系统中均可见,所以它们可用于跨进程边界协调资源使用。Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

若要确定是否存在已命名的系统信号量,请使用 OpenExisting 方法。If you want to find out whether a named system semaphore exists, use the OpenExisting method. OpenExisting 方法尝试打开现有的已命名信号量,并在系统信号量不存在时引发异常。The OpenExisting method attempts to open an existing named semaphore, and throws an exception if the system semaphore does not exist.

安全性

SecurityPermission
用于调用非托管代码以创建已命名的系统信号量。for calling unmanaged code to create a named system semaphore. 关联的枚举:UnmanagedCodeAssociated enumeration: UnmanagedCode. 安全操作: LinkDemandSecurity action: LinkDemand.

另请参阅

Semaphore(Int32, Int32, String, Boolean)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数,还可以选择指定系统信号量对象的名称,以及指定一个变量来接收指示是否创建了新系统信号量的值。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, and specifying a variable that receives a value indicating whether a new system semaphore was created.

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
public Semaphore (int initialCount, int maximumCount, string name, out bool createdNew);
new System.Threading.Semaphore : int * int * string * bool -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String, ByRef createdNew As Boolean)

参数

initialCount
Int32

可以同时满足的信号量的初始请求数。The initial number of requests for the semaphore that can be satisfied concurrently.

maximumCount
Int32

可以同时满足的信号量的最大请求数。The maximum number of requests for the semaphore that can be satisfied concurrently.

name
String

命名系统信号量对象的名称。The name of a named system semaphore object.

createdNew
Boolean

在此方法返回时,如果创建了本地信号量(即,如果 truename 或空字符串)或指定的命名系统信号量,则包含 null;如果指定的命名系统信号量已存在,则为 falseWhen this method returns, contains true if a local semaphore was created (that is, if name is null or an empty string) or if the specified named system semaphore was created; false if the specified named system semaphore already existed. 此参数未经初始化即被传递。This parameter is passed uninitialized.

异常

initialCount 大于 maximumCountinitialCount is greater than maximumCount.

- 或 --or- name 超过 260 个字符。name is longer than 260 characters.

maximumCount 小于 1。maximumCount is less than 1.

- 或 --or- initialCount 小于 0。initialCount is less than 0.

出现 Win32 错误。A Win32 error occurred.

命名信号量存在且具有访问控制安全性,用户不具有 FullControlThe named semaphore exists and has access control security, and the user does not have FullControl.

无法创建命名信号量,可能是由于其他类型的等待句柄具有相同名称。The named semaphore cannot be created, perhaps because a wait handle of a different type has the same name.

示例

下面的代码示例演示命名信号量的跨进程行为。The following code example demonstrates the cross-process behavior of a named semaphore. 该示例创建一个名为的信号量,其最大计数为5,初始计数为2。The example creates a named semaphore with a maximum count of five and an initial count of two. 也就是说,它为调用构造函数的线程保留了三个条目。That is, it reserves three entries for the thread that calls the constructor. 如果 false``createNew,程序将对 WaitOne 方法进行三次调用。If createNew is false, the program makes three calls to the WaitOne method. 因此,如果从两个命令窗口运行已编译的示例,第二个副本会阻止第三次调用 WaitOneThus, if you run the compiled example from two command windows, the second copy will block on the third call to WaitOne. 释放程序的第一个副本中的一个或多个项以解除阻止第二个副本。Release one or more entries in the first copy of the program to unblock the second.

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // 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 a Semaphore object that represents the named
      // system semaphore "SemaphoreExample". The semaphore has a
      // maximum count of five, and an initial count of two. The
      // Boolean value that indicates creation of the underlying
      // system object is placed in semaphoreWasCreated.
      //
      Semaphore^ sem = gcnew Semaphore( 2,5,L"SemaphoreExample",
         semaphoreWasCreated );
      if ( semaphoreWasCreated )
      {
         // If the named system semaphore was created, its count is
         // set to the initial count requested in the constructor.
         // In effect, the current thread has entered the semaphore
         // three times.
         //
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      else
      {
         // If the named system semaphore was not created,
         // attempt to enter it three times. If another copy of
         // this program is already running, only the first two
         // requests can be satisfied. The third blocks.
         //
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore once." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore twice." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release." );
      int n;
      if ( Int32::TryParse( Console::ReadLine(), n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // 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 a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample". The semaphore has a
        // maximum count of five, and an initial count of two. The
        // Boolean value that indicates creation of the underlying 
        // system object is placed in semaphoreWasCreated.
        //
        Semaphore sem = new Semaphore(2, 5, "SemaphoreExample", 
            out semaphoreWasCreated);

        if (semaphoreWasCreated)
        {
            // If the named system semaphore was created, its count is
            // set to the initial count requested in the constructor.
            // In effect, the current thread has entered the semaphore
            // three times.
            // 
            Console.WriteLine("Entered the semaphore three times.");
        }
        else
        {      
            // If the named system semaphore was not created,  
            // attempt to enter it three times. If another copy of
            // this program is already running, only the first two
            // requests can be satisfied. The third blocks.
            //
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore once.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore twice.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore three times.");
        }

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    } 
} 
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' 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 a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample". The semaphore has a
        ' maximum count of five, and an initial count of two. The
        ' Boolean value that indicates creation of the underlying 
        ' system object is placed in semaphoreWasCreated.
        '
        Dim sem As New Semaphore(2, 5, "SemaphoreExample", _
            semaphoreWasCreated)

        If semaphoreWasCreated Then
            ' If the named system semaphore was created, its count is
            ' set to the initial count requested in the constructor.
            ' In effect, the current thread has entered the semaphore
            ' three times.
            ' 
            Console.WriteLine("Entered the semaphore three times.")
        Else
            ' If the named system semaphore was not created,  
            ' attempt to enter it three times. If another copy of
            ' this program is already running, only the first two
            ' requests can be satisfied. The third blocks.
            '
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore once.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore twice.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore three times.")
        End If

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(), n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining " _
                & "count ({0}) and exit the program.", remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class 

注解

此构造函数初始化表示已命名的系统信号量的 Semaphore 对象。This constructor initializes a Semaphore object that represents a named system semaphore. 可以创建多个表示同一命名系统信号量的 Semaphore 对象。You can create multiple Semaphore objects that represent the same named system semaphore.

如果已命名的系统信号量不存在,则使用 initialCountmaximumCount指定的初始计数和最大计数来创建它。If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 如果已命名的系统信号量已存在,则不会使用 initialCountmaximumCount,尽管无效值仍然会导致异常。If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. 使用 createdNew 来确定是否已创建系统信号量。Use createdNew to determine whether the system semaphore was created.

如果 initialCount 小于 maximumCount并且 createdNew true,则效果与当前线程已调用 WaitOnemaximumCountinitialCount)次相同。If initialCount is less than maximumCount, and createdNew is true, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times.

如果为 name指定 null 或空字符串,则将创建一个本地信号量,就像您已经调用了 Semaphore(Int32, Int32) 构造函数重载一样。If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload. 在这种情况下,始终 true``createdNewIn this case, createdNew is always true.

因为命名的信号量在整个操作系统中均可见,所以它们可用于跨进程边界协调资源使用。Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

安全性

SecurityPermission
用于调用非托管代码以创建已命名的系统信号量。for calling unmanaged code to create a named system semaphore. 关联的枚举:UnmanagedCodeAssociated enumeration: UnmanagedCode. 安全操作: LinkDemandSecurity action: LinkDemand.

另请参阅

Semaphore(Int32, Int32, String, Boolean, SemaphoreSecurity)

初始化 Semaphore 类的新实例,并指定初始入口数和最大并发入口数,可以选择指定系统信号量对象的名称,指定一个变量来接收指示是否创建了新系统信号量的值,以及指定系统信号量的安全访问控制。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, specifying a variable that receives a value indicating whether a new system semaphore was created, and specifying security access control for the system semaphore.

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::SemaphoreSecurity ^ semaphoreSecurity);
public Semaphore (int initialCount, int maximumCount, string name, out bool createdNew, System.Security.AccessControl.SemaphoreSecurity semaphoreSecurity);
new System.Threading.Semaphore : int * int * string * bool * System.Security.AccessControl.SemaphoreSecurity -> System.Threading.Semaphore

参数

initialCount
Int32

可以同时满足的信号量的初始请求数。The initial number of requests for the semaphore that can be satisfied concurrently.

maximumCount
Int32

可以同时满足的信号量的最大请求数。The maximum number of requests for the semaphore that can be satisfied concurrently.

name
String

命名系统信号量对象的名称。The name of a named system semaphore object.

createdNew
Boolean

在此方法返回时,如果创建了本地信号量(即,如果 truename 或空字符串)或指定的命名系统信号量,则包含 null;如果指定的命名系统信号量已存在,则为 falseWhen this method returns, contains true if a local semaphore was created (that is, if name is null or an empty string) or if the specified named system semaphore was created; false if the specified named system semaphore already existed. 此参数未经初始化即被传递。This parameter is passed uninitialized.

semaphoreSecurity
SemaphoreSecurity

一个 SemaphoreSecurity 对象,表示应用于已命名的系统信号量的访问控制安全性。A SemaphoreSecurity object that represents the access control security to be applied to the named system semaphore.

异常

initialCount 大于 maximumCountinitialCount is greater than maximumCount.

- 或 --or- name 超过 260 个字符。name is longer than 260 characters.

maximumCount 小于 1。maximumCount is less than 1.

- 或 --or- initialCount 小于 0。initialCount is less than 0.

命名信号量存在且具有访问控制安全性,用户不具有 FullControlThe named semaphore exists and has access control security, and the user does not have FullControl.

出现 Win32 错误。A Win32 error occurred.

无法创建命名信号量,可能是由于其他类型的等待句柄具有相同名称。The named semaphore cannot be created, perhaps because a wait handle of a different type has the same name.

示例

下面的代码示例演示具有访问控制安全性的命名信号量的跨进程行为。The following code example demonstrates the cross-process behavior of a named semaphore with access control security. 该示例使用 OpenExisting(String) 方法重载来测试是否存在已命名的信号量。The example uses the OpenExisting(String) method overload to test for the existence of a named semaphore. 如果该信号量不存在,则将创建该信号量的最大计数为2且具有访问控制安全性,这会拒绝当前用户使用该信号量,但会授予读取和更改信号量权限的权限。If the semaphore does not exist, it is created with a maximum count of two and with access control security that denies the current user the right to use the semaphore but grants the right to read and change permissions on the semaphore. 如果从两个命令窗口运行已编译的示例,第二个副本将在调用 OpenExisting(String) 方法时引发访问冲突异常。If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to the OpenExisting(String) method. 捕获到异常,该示例使用 OpenExisting(String, SemaphoreRights) 方法重载打开具有读取和更改权限所需权限的信号量。The exception is caught, and the example uses the OpenExisting(String, SemaphoreRights) method overload to open the semaphore with the rights needed to read and change the permissions.

更改权限后,会打开信号量,其中包含进入和释放所需的权限。After the permissions are changed, the semaphore is opened with the rights required to enter and release. 如果从第三个命令窗口运行已编译的示例,该示例将使用新的权限运行。If you run the compiled example from a third command window, it runs using the new permissions.

#using <System.dll>
using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand, Flags = SecurityPermissionFlag::UnmanagedCode)]
   static void main()
   {
      String^ semaphoreName = L"SemaphoreExample5";

      Semaphore^ sem = nullptr;
      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^ ex ) 
      {
         Console::WriteLine( L"Semaphore does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"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 = String::Concat( Environment::UserDomainName,
            L"\\", Environment::UserName );
         SemaphoreSecurity^ semSec = gcnew SemaphoreSecurity;

         SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               SemaphoreRights::Synchronize |
               SemaphoreRights::Modify ),
            AccessControlType::Deny );
         semSec->AddAccessRule( rule );

         rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               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 = gcnew 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 )
         {
            Console::WriteLine( L"Created the semaphore." );
         }
         else
         {
            Console::WriteLine( L"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,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::ReadPermissions |
                  SemaphoreRights::ChangePermissions ));
            
            // Get the current ACL. This requires
            // SemaphoreRights.ReadPermissions.
            SemaphoreSecurity^ semSec = sem->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the semaphore must
            // be removed.
            SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::Synchronize |
                  SemaphoreRights::Modify ),
               AccessControlType::Deny );
            semSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew SemaphoreAccessRule( user,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::Synchronize |
                  SemaphoreRights::Modify ),
               AccessControlType::Allow );
            semSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // SemaphoreRights.ChangePermissions.
            sem->SetAccessControl( semSec );

            Console::WriteLine( L"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( L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }
      
      // Enter the semaphore, and hold it until the program
      // exits.
      //
      try
      {
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore." );
         Console::WriteLine( L"Press the Enter key to exit." );
         Console::ReadLine();
         sem->Release();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
   }
};
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 

注解

使用此构造函数可在创建已命名的系统信号量时对其应用访问控制安全性,从而阻止其他代码控制信号量。Use this constructor to apply access control security to a named system semaphore when it is created, preventing other code from taking control of the semaphore.

此构造函数初始化表示已命名的系统信号量的 Semaphore 对象。This constructor initializes a Semaphore object that represents a named system semaphore. 可以创建多个表示同一命名系统信号量的 Semaphore 对象。You can create multiple Semaphore objects that represent the same named system semaphore.

如果已命名的系统信号量不存在,则将使用指定的访问控制安全性来创建它。If the named system semaphore does not exist, it is created with the specified access control security. 如果已命名的信号量存在,则将忽略指定的访问控制安全性。If the named semaphore exists, the specified access control security is ignored.

备注

即使 semaphoreSecurity 拒绝或无法向当前用户授予某些访问权限,调用方仍可以完全控制新创建的 Semaphore 对象。The caller has full control over the newly created Semaphore object even if semaphoreSecurity denies or fails to grant some access rights to the current user. 但是,如果当前用户尝试使用构造函数或 OpenExisting 方法获取另一个 Semaphore 对象来表示相同的命名信号量,则应用 Windows 访问控制安全性。However, if the current user attempts to get another Semaphore object to represent the same named semaphore, using either a constructor or the OpenExisting method, Windows access control security is applied.

如果已命名的系统信号量不存在,则使用 initialCountmaximumCount指定的初始计数和最大计数来创建它。If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 如果已命名的系统信号量已存在,则不会使用 initialCountmaximumCount,尽管无效值仍然会导致异常。If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. 使用 createdNew 参数确定系统信号量是否是由此构造函数创建的。Use the createdNew parameter to determine whether the system semaphore was created by this constructor.

如果 initialCount 小于 maximumCount并且 createdNew true,则效果与当前线程已调用 WaitOnemaximumCountinitialCount)次相同。If initialCount is less than maximumCount, and createdNew is true, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times.

如果为 name指定 null 或空字符串,则将创建一个本地信号量,就像您已经调用了 Semaphore(Int32, Int32) 构造函数重载一样。If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload. 在这种情况下,始终 true``createdNewIn this case, createdNew is always true.

因为命名的信号量在整个操作系统中均可见,所以它们可用于跨进程边界协调资源使用。Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

安全性

SecurityPermission
用于调用非托管代码以创建已命名的系统信号量。for calling unmanaged code to create a named system semaphore. 关联的枚举:UnmanagedCodeAssociated enumeration: UnmanagedCode. 安全操作: LinkDemandSecurity action: LinkDemand.

另请参阅

适用于