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.

範例

下列範例會建立最多三個計數和初始計數為零的信號。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 效果與目前線程呼叫 WaitOne (maximumCount 減去 initialCount) 次時相同。If initialCount is less than maximumCount, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. 如果您不想要為建立信號的執行緒保留任何專案,請使用和的相同號碼 maximumCount initialCountIf 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);
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

如果同步物件要與其他處理序共用,則為名稱;否則為 null 或空字串。The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. 名稱區分大小寫。The name is case-sensitive.

例外狀況

initialCount 大於 maximumCountinitialCount is greater than maximumCount.

-或--or-

僅限 .NET Framework:name 的長度超過 MAX_PATH (260 個字元)。.NET Framework only: name is longer than MAX_PATH (260 characters).

maximumCount 小於 1。maximumCount is less than 1.

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

name 無效。name is invalid. 這可能基於數種原因,其中包括可能由作業系統設定的一些限制,例如未知前置詞或無效字元。This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 請注意,名稱與通用前置詞 "Global" 與 "Local" 會區分大小寫。Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-或--or-

發生一些其他錯誤。There was some other error. HResult 屬性可提供詳細資訊。The HResult property may provide more information.

僅限 Windows:name 已指定未知命名空間。Windows only: name specified an unknown namespace. 請參閱物件名稱 (英文) 以取得詳細資訊。See Object Names for more information.

name 太長。The name is too long. 長度限制可能會取決於作業系統或設定。Length restrictions may depend on the operating system or configuration.

具名信號已存在,並且具有存取控制安全性,而使用者沒有 FullControlThe named semaphore exists and has access control security, and the user does not have FullControl.

無法建立具有所提供 name 的同步物件。A synchronization object with the provided name cannot be created. 不同類型的同步物件可能具有相同名稱。A synchronization object of a different type might have 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. 此程式會對方法進行三次呼叫 WaitOneThe 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.

name可能會在前面加上 Global\Local\ 來指定命名空間。The name may be prefixed with Global\ or Local\ to specify a namespace. Global指定命名空間時,同步處理物件可能會與系統上的任何處理程式共用。When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Local 指定命名空間時,如果未指定命名空間,這也是預設值,則可以與相同會話中的處理常式共用同步處理物件。When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 在 Windows 上,會話是登入會話,而服務通常會在不同的非互動式會話中執行。On Windows, a session is a login session, and services typically run in a different non-interactive session. 在類似 Unix 的作業系統上,每個 shell 都有自己的會話。On Unix-like operating systems, each shell has its own session. 會話本機同步處理物件可能適合用來在具有父/子關聯性的進程之間進行同步處理,而且它們都會在相同的會話中執行。Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. 如需有關在 Windows 上 synchornization 物件名稱的詳細資訊,請參閱 物件名稱For more information about synchornization object names on Windows, see Object Names.

如果 name 已提供,且命名空間中已有所要求類型的同步處理物件存在,就會使用現有的同步處理物件。If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. 如果命名空間中已經有不同類型的同步處理物件存在, WaitHandleCannotBeOpenedException 就會擲回。If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. 否則會建立新的同步處理物件。Otherwise, a new synchronization object is created.

如果命名的系統信號不存在,就會使用和指定的初始計數和最大計數來建立它 initialCount maximumCountIf the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 如果已存在命名的系統信號, initialCount 而且 maximumCount 未使用,雖然不正確值仍會造成例外狀況。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.

重要

當您使用這個函式多載時,建議的作法是為和指定相同的數位 initialCount maximumCountWhen you use this constructor overload, the recommended practice is to specify the same number for initialCount and maximumCount. 如果 initialCount 小於 maximumCount ,而且已建立命名系統信號,則效果會與目前線程呼叫 WaitOne (maximumCount 減去 initialCount) 次時相同。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.

如果您指定 null 或的空字串 name ,則會建立本機信號,就像您呼叫了函式多載一樣 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.

適用於

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);
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

如果同步物件要與其他處理序共用,則為名稱;否則為 null 或空字串。The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. 名稱區分大小寫。The name is case-sensitive.

createdNew
Boolean

這個方法傳回時,如果已建立本機號誌 (也就是說,如果 namenull 或空字串),或是已建立指定的已命名系統號誌,則會包含 true;如果指定的已命名系統號誌已存在則為 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-

僅限 .NET Framework:name 的長度超過 MAX_PATH (260 個字元)。.NET Framework only: name is longer than MAX_PATH (260 characters).

maximumCount 小於 1。maximumCount is less than 1.

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

name 無效。name is invalid. 這可能基於數種原因,其中包括可能由作業系統設定的一些限制,例如未知前置詞或無效字元。This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 請注意,名稱與通用前置詞 "Global" 與 "Local" 會區分大小寫。Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-或--or-

發生一些其他錯誤。There was some other error. HResult 屬性可提供詳細資訊。The HResult property may provide more information.

僅限 Windows:name 已指定未知命名空間。Windows only: name specified an unknown namespace. 請參閱物件名稱 (英文) 以取得詳細資訊。See Object Names for more information.

name 太長。The name is too long. 長度限制可能會取決於作業系統或設定。Length restrictions may depend on the operating system or configuration.

具名信號已存在,並且具有存取控制安全性,而使用者沒有 FullControlThe named semaphore exists and has access control security, and the user does not have FullControl.

無法建立具有所提供 name 的同步物件。A synchronization object with the provided name cannot be created. 不同類型的同步物件可能具有相同名稱。A synchronization object of a different type might have 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. 如果 createNewfalse ,則程式會對方法進行三次呼叫 WaitOneIf 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 

備註

name可能會在前面加上 Global\Local\ 來指定命名空間。The name may be prefixed with Global\ or Local\ to specify a namespace. Global指定命名空間時,同步處理物件可能會與系統上的任何處理程式共用。When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Local 指定命名空間時,如果未指定命名空間,這也是預設值,則可以與相同會話中的處理常式共用同步處理物件。When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 在 Windows 上,會話是登入會話,而服務通常會在不同的非互動式會話中執行。On Windows, a session is a login session, and services typically run in a different non-interactive session. 在類似 Unix 的作業系統上,每個 shell 都有自己的會話。On Unix-like operating systems, each shell has its own session. 會話本機同步處理物件可能適合用來在具有父/子關聯性的進程之間進行同步處理,而且它們都會在相同的會話中執行。Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. 如需有關在 Windows 上 synchornization 物件名稱的詳細資訊,請參閱 物件名稱For more information about synchornization object names on Windows, see Object Names.

如果 name 已提供,且命名空間中已有所要求類型的同步處理物件存在,就會使用現有的同步處理物件。If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. 如果命名空間中已經有不同類型的同步處理物件存在, WaitHandleCannotBeOpenedException 就會擲回。If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. 否則會建立新的同步處理物件。Otherwise, a new synchronization object is created.

這個函式 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.

如果命名的系統信號不存在,就會使用和指定的初始計數和最大計數來建立它 initialCount maximumCountIf the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 如果已存在命名的系統信號, initialCount 而且 maximumCount 未使用,雖然不正確值仍會造成例外狀況。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 效果會與目前線程呼叫 WaitOne (maximumCount 減去 initialCount) 次時相同。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.

如果您指定 null 或的空字串 name ,則會建立本機信號,就像您呼叫了函式多載一樣 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. 在此情況下, createdNew 一律為 trueIn 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.

適用於

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
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String, ByRef createdNew As Boolean, semaphoreSecurity As SemaphoreSecurity)

參數

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

如果同步物件要與其他處理序共用,則為名稱;否則為 null 或空字串。The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. 名稱區分大小寫。The name is case-sensitive.

createdNew
Boolean

這個方法傳回時,如果已建立本機號誌 (也就是說,如果 namenull 或空字串),或是已建立指定的已命名系統號誌,則會包含 true;如果指定的已命名系統號誌已存在則為 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-

僅限 .NET Framework:name 的長度超過 MAX_PATH (260 個字元)。.NET Framework only: name is longer than MAX_PATH (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.

name 無效。name is invalid. 這可能基於數種原因,其中包括可能由作業系統設定的一些限制,例如未知前置詞或無效字元。This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 請注意,名稱與通用前置詞 "Global" 與 "Local" 會區分大小寫。Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-或--or-

發生一些其他錯誤。There was some other error. HResult 屬性可提供詳細資訊。The HResult property may provide more information.

僅限 Windows:name 已指定未知命名空間。Windows only: name specified an unknown namespace. 請參閱物件名稱 (英文) 以取得詳細資訊。See Object Names for more information.

name 太長。The name is too long. 長度限制可能會取決於作業系統或設定。Length restrictions may depend on the operating system or configuration.

無法建立具有所提供 name 的同步物件。A synchronization object with the provided name cannot be created. 不同類型的同步物件可能具有相同名稱。A synchronization object of a different type might have 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. 如果信號不存在,則會使用最大的計數來建立,並使用存取控制安全性來拒絕目前使用者使用該信號的許可權,但會授與對信號的讀取和變更許可權許可權。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.

name可能會在前面加上 Global\Local\ 來指定命名空間。The name may be prefixed with Global\ or Local\ to specify a namespace. Global指定命名空間時,同步處理物件可能會與系統上的任何處理程式共用。When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Local 指定命名空間時,如果未指定命名空間,這也是預設值,則可以與相同會話中的處理常式共用同步處理物件。When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 在 Windows 上,會話是登入會話,而服務通常會在不同的非互動式會話中執行。On Windows, a session is a login session, and services typically run in a different non-interactive session. 在類似 Unix 的作業系統上,每個 shell 都有自己的會話。On Unix-like operating systems, each shell has its own session. 會話本機同步處理物件可能適合用來在具有父/子關聯性的進程之間進行同步處理,而且它們都會在相同的會話中執行。Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. 如需有關在 Windows 上 synchornization 物件名稱的詳細資訊,請參閱 物件名稱For more information about synchornization object names on Windows, see Object Names.

如果 name 已提供,且命名空間中已有所要求類型的同步處理物件存在,就會使用現有的同步處理物件。If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. 如果命名空間中已經有不同類型的同步處理物件存在, WaitHandleCannotBeOpenedException 就會擲回。If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. 否則會建立新的同步處理物件。Otherwise, a new synchronization object is created.

這個函式 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.

注意

Semaphore即使 semaphoreSecurity 拒絕或無法授與存取權給目前的使用者,呼叫者仍能完全掌控新建立的物件。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. 但是,如果目前的使用者嘗試使用函式 Semaphore 或方法,取得另一個物件來代表相同的命名信號, OpenExisting 就會套用 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.

如果命名的系統信號不存在,就會使用和指定的初始計數和最大計數來建立它 initialCount maximumCountIf the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 如果已存在命名的系統信號, initialCount 而且 maximumCount 未使用,雖然不正確值仍會造成例外狀況。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 效果會與目前線程呼叫 WaitOne (maximumCount 減去 initialCount) 次時相同。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.

如果您指定 null 或的空字串 name ,則會建立本機信號,就像您呼叫了函式多載一樣 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. 在此情況下, createdNew 一律為 trueIn 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.

適用於