Semaphore Oluşturucular

Tanım

Semaphore sınıfının yeni bir örneğini başlatır.

Aşırı Yüklemeler

Semaphore(Int32, Int32)

İlk girdi sayısını ve eşzamanlı girdi sayısı üst sınırını belirterek sınıfının yeni bir örneğini Semaphore başlatır.

Semaphore(Int32, Int32, String)

İlk girdi sayısını ve eşzamanlı girdi sayısı üst sınırını belirterek ve isteğe bağlı olarak sistem semafor nesnesinin adını belirterek sınıfının yeni bir örneğini Semaphore başlatır.

Semaphore(Int32, Int32, String, Boolean)

sınıfının yeni bir örneğini Semaphore başlatır, ilk girdi sayısını ve en fazla eşzamanlı girdi sayısını belirtir, isteğe bağlı olarak bir sistem semafor nesnesinin adını belirtir ve yeni bir sistem semaforunun oluşturulup oluşturulmadığını belirten bir değer alan bir değişken belirtir.

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

sınıfının yeni bir örneğini Semaphore başlatır, ilk girdi sayısını ve en fazla eş zamanlı girdi sayısını belirtir, isteğe bağlı olarak sistem semafor nesnesinin adını belirtir, yeni bir sistem semaforu oluşturulup oluşturulmadığını belirten bir değer alan bir değişken belirtir ve sistem semaforu için güvenlik erişim denetimi belirtir.

Semaphore(Int32, Int32)

Kaynak:
Semaphore.cs
Kaynak:
Semaphore.cs
Kaynak:
Semaphore.cs

İlk girdi sayısını ve eşzamanlı girdi sayısı üst sınırını belirterek sınıfının yeni bir örneğini Semaphore başlatır.

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)

Parametreler

initialCount
Int32

Semafor için eşzamanlı olarak verilebilen ilk istek sayısı.

maximumCount
Int32

Semafor için eşzamanlı olarak verilebilen istek sayısı üst sınırı.

Özel durumlar

initialCount değerinden büyüktür maximumCount.

maximumCount 1'den küçüktür.

-veya-

initialCount 0'dan küçüktür.

Örnekler

Aşağıdaki örnek, en fazla üç ve başlangıç sayısı sıfır olan bir semafor oluşturur. Örnek, semafor beklemeyi engelleyen beş iş parçacığı başlatır. Ana iş parçacığı, semafor sayısını maksimuma yükseltmek için yöntem aşırı yüklemesini kullanarak Release(Int32) üç iş parçacığının semafora girmesine izin verir. Her iş parçacığı, çalışmanın benzetimini Thread.Sleep yapmak için bir saniye beklemek için yöntemini kullanır ve ardından semaforu Release() serbest bırakmak için yöntem aşırı yüklemesini çağırır. Semafor her serbest bırakıldığında, önceki semafor sayısı görüntülenir. Konsol iletileri semafor kullanımını izler. Simülasyon çalışma aralığı, çıkışın okunmasını kolaylaştırmak için her iş parçacığı için biraz artırılır.

#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(initialCount: 0, maximumCount: 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(releaseCount: 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

Açıklamalar

Bu oluşturucu adlandırılmamış bir semafor başlatır. Böyle bir semafor örneğini kullanan tüm iş parçacıklarının örneğe başvuruları olmalıdır.

değerinden küçükse initialCountmaximumCount, geçerli iş parçacığının (maximumCount eksi initialCount) kez çağırmış WaitOne olmasıyla aynı etkidir. Semaforu oluşturan iş parçacığı için herhangi bir girdi ayırmak istemiyorsanız, ve initialCountiçin maximumCount aynı sayıyı kullanın.

Ayrıca bkz.

Şunlara uygulanır

Semaphore(Int32, Int32, String)

Kaynak:
Semaphore.cs
Kaynak:
Semaphore.cs
Kaynak:
Semaphore.cs

İlk girdi sayısını ve eşzamanlı girdi sayısı üst sınırını belirterek ve isteğe bağlı olarak sistem semafor nesnesinin adını belirterek sınıfının yeni bir örneğini Semaphore başlatır.

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)

Parametreler

initialCount
Int32

Semafor için eşzamanlı olarak verilebilen ilk istek sayısı.

maximumCount
Int32

Semafor için eşzamanlı olarak verilebilen istek sayısı üst sınırı.

name
String

Eşitleme nesnesi diğer işlemlerle paylaşılacaksa adı; null veya boş bir dize. Bu ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde ad alanı dışladıktan sonra adın geçerli bir dosya adı olması gerekir.

Özel durumlar

initialCount değerinden büyüktür maximumCount.

-veya-

Yalnızca .NET Framework: name MAX_PATH(260 karakter) uzundur.

maximumCount 1'den küçüktür.

-veya-

initialCount 0'dan küçüktür.

name geçersizdir. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilen bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve ortak ön eklerin "Genel\" ve "Yerel\" büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. Özelliği HResult daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz . Nesne Adları .

name Çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Adlandırılmış semafor var ve erişim denetimi güvenliğine sahip ve kullanıcının yok FullControl.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.

Örnekler

Aşağıdaki kod örneği, adlandırılmış bir semaforun çapraz işlem davranışını gösterir. Örnek, en fazla beş ve ilk sayısı beş olan adlandırılmış bir semafor oluşturur. Program yöntemine WaitOne üç çağrı yapar. Bu nedenle, derlenmiş örneği iki komut penceresiyle çalıştırırsanız, ikinci kopya üçüncü çağrısında WaitOneöğesini engeller. İkincinin engelini kaldırmak için programın ilk kopyasındaki bir veya daha fazla girdiyi serbest bırakın.

#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

Açıklamalar

Bu oluşturucu, adlandırılmış sistem Semaphore semaforu temsil eden bir nesne başlatır. Aynı adlandırılmış sistem semaforunu temsil eden birden çok Semaphore nesne oluşturabilirsiniz.

name bir ad alanı belirtmek için veya Local\ ön ekine Global\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows'da oturum bir oturum açma oturumudur ve hizmetler genellikle farklı bir etkileşimli olmayan oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, işlemlerin aynı oturumda çalıştırıldığı bir üst/alt ilişki ile eşitleme için uygun olabilir. Windows'da eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Nesne Adları.

bir name sağlanırsa ve istenen türdeki bir eşitleme nesnesi ad alanında zaten varsa, var olan eşitleme nesnesi kullanılır. Ad alanında farklı türde bir eşitleme nesnesi zaten varsa, bir WaitHandleCannotBeOpenedException oluşturulur. Aksi takdirde, yeni bir eşitleme nesnesi oluşturulur.

Adlandırılmış sistem semaforu yoksa, ve maximumCounttarafından initialCount belirtilen ilk sayı ve maksimum sayı ile oluşturulur. Adlandırılmış sistem semaforu zaten varsa initialCount ve maximumCount kullanılmıyorsa, ancak geçersiz değerler yine de özel durumlara neden olur. Adlandırılmış bir sistem semaforunun oluşturulup oluşturulmadığını belirlemeniz gerekiyorsa, bunun yerine oluşturucu aşırı yüklemesini Semaphore(Int32, Int32, String, Boolean) kullanın.

Önemli

Bu oluşturucu aşırı yüklemesini kullandığınızda, önerilen uygulama ve maximumCountiçin initialCount aynı sayıyı belirtmektir. değerinden maximumCountküçükse ve adlandırılmış bir sistem semaforu oluşturulduysainitialCount, etki geçerli iş parçacığının (maximumCount eksi initialCount) kez çağırmış WaitOne olmasıyla aynıdır. Ancak, bu oluşturucu aşırı yüklemesi ile adlandırılmış bir sistem semaforu oluşturulup oluşturulmadığını belirlemenin bir yolu yoktur.

için veya için nameboş bir dize belirtirseniznull, oluşturucu aşırı yüklemesini çağırmış Semaphore(Int32, Int32) gibi yerel bir semafor oluşturulur.

Adlandırılmış semaforlar işletim sistemi genelinde görünür olduğundan, kaynak kullanımını işlem sınırları arasında koordine etmek için kullanılabilir.

Adlandırılmış sistem semaforunun var olup olmadığını öğrenmek istiyorsanız yöntemini kullanın OpenExisting . OpenExisting yöntemi, adlandırılmış mevcut bir semafor açmayı dener ve sistem semaforu yoksa bir özel durum oluşturur.

Dikkat

Varsayılan olarak, adlandırılmış bir semafor onu oluşturan kullanıcıyla sınırlı değildir. Diğer kullanıcılar semaforu birden çok kez alarak ve serbest bırakmayarak semafora müdahale etmek de dahil olmak üzere semaforu açabilir ve kullanabilir. Erişimi belirli kullanıcılarla kısıtlamak için bir oluşturucu aşırı yüklemesi kullanabilir veya SemaphoreAcl adlandırılmış semaforu oluştururken bir SemaphoreSecurity geçirebilirsiniz. Kod çalıştıran güvenilmeyen kullanıcıların olabileceği sistemlerde erişim kısıtlamaları olmadan adlandırılmış semafor kullanmaktan kaçının.

Ayrıca bkz.

Şunlara uygulanır

Semaphore(Int32, Int32, String, Boolean)

Kaynak:
Semaphore.cs
Kaynak:
Semaphore.cs
Kaynak:
Semaphore.cs

sınıfının yeni bir örneğini Semaphore başlatır, ilk girdi sayısını ve en fazla eşzamanlı girdi sayısını belirtir, isteğe bağlı olarak bir sistem semafor nesnesinin adını belirtir ve yeni bir sistem semaforunun oluşturulup oluşturulmadığını belirten bir değer alan bir değişken belirtir.

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)

Parametreler

initialCount
Int32

Semafor için eşzamanlı olarak karşılanabilecek ilk istek sayısı.

maximumCount
Int32

Semafor için eşzamanlı olarak karşılanabilecek en fazla istek sayısı.

name
String

Eşitleme nesnesi diğer işlemlerle paylaşılacaksa adı; null veya boş bir dize. Bu ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde ad alanı dışladıktan sonra adın geçerli bir dosya adı olması gerekir.

createdNew
Boolean

Bu yöntem döndürdüğünde, yerel bir semafor oluşturulup oluşturulmadığını (varsa nullname veya boş bir dize) veya belirtilen adlandırılmış sistem semaforunun oluşturulup oluşturulmadığını; false belirtilen adlandırılmış sistem semaforunun zaten mevcut olup olmadığını içerirtrue. Bu parametre, başlatmadan iletilir.

Özel durumlar

initialCount değerinden büyüktür maximumCount.

-veya-

Yalnızca .NET Framework: name MAX_PATH(260 karakter) uzundur.

maximumCount 1'den küçüktür.

-veya-

initialCount 0'dan küçüktür.

name geçersizdir. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilen bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve ortak ön eklerin "Genel\" ve "Yerel\" büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. Özelliği HResult daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz . Nesne Adları .

name Çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Adlandırılmış semafor var ve erişim denetimi güvenliğine sahip ve kullanıcının yok FullControl.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.

Örnekler

Aşağıdaki kod örneği, adlandırılmış bir semaforun çapraz işlem davranışını gösterir. Örnek, en fazla beş ve ilk sayısı iki olan adlandırılmış bir semafor oluşturur. Başka bir ifadeyle, oluşturucuyu çağıran iş parçacığı için üç giriş ayırır. ise createNewfalse, program yöntemine WaitOne üç çağrı yapar. Bu nedenle, derlenmiş örneği iki komut penceresiyle çalıştırırsanız, ikinci kopya üçüncü çağrısında WaitOneöğesini engeller. İkincinin engelini kaldırmak için programın ilk kopyasındaki bir veya daha fazla girdiyi serbest bırakın.

#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

Açıklamalar

name bir ad alanı belirtmek için veya Local\ ön ekine Global\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows'da oturum bir oturum açma oturumudur ve hizmetler genellikle farklı bir etkileşimli olmayan oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, işlemlerin aynı oturumda çalıştırıldığı bir üst/alt ilişki ile eşitleme için uygun olabilir. Windows'da eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Nesne Adları.

bir name sağlanırsa ve istenen türdeki bir eşitleme nesnesi ad alanında zaten varsa, var olan eşitleme nesnesi kullanılır. Ad alanında farklı türde bir eşitleme nesnesi zaten varsa, bir WaitHandleCannotBeOpenedException oluşturulur. Aksi takdirde, yeni bir eşitleme nesnesi oluşturulur.

Bu oluşturucu, adlandırılmış sistem Semaphore semaforu temsil eden bir nesne başlatır. Aynı adlandırılmış sistem semaforunu temsil eden birden çok Semaphore nesne oluşturabilirsiniz.

Adlandırılmış sistem semaforu yoksa, ve maximumCounttarafından initialCount belirtilen ilk sayı ve maksimum sayı ile oluşturulur. Adlandırılmış sistem semaforu zaten varsa initialCount ve maximumCount kullanılmıyorsa, ancak geçersiz değerler yine de özel durumlara neden olur. Sistem semaforunun oluşturulup oluşturulmadığını belirlemek için kullanın createdNew .

değerinden küçükse initialCount ve createdNew isetrue, geçerli iş parçacığının (maximumCount eksi initialCount) kez çağırmış WaitOne olmasıyla aynıdır.maximumCount

için veya için nameboş bir dize belirtirseniznull, oluşturucu aşırı yüklemesini çağırmış Semaphore(Int32, Int32) gibi yerel bir semafor oluşturulur. Bu durumda, createdNew her zaman trueolur.

Adlandırılmış semaforlar işletim sistemi genelinde görünür olduğundan, kaynak kullanımını işlem sınırları arasında koordine etmek için kullanılabilir.

Dikkat

Varsayılan olarak, adlandırılmış bir semafor onu oluşturan kullanıcıyla sınırlı değildir. Diğer kullanıcılar semaforu birden çok kez alarak ve serbest bırakmayarak semafora müdahale etmek de dahil olmak üzere semaforu açabilir ve kullanabilir. Erişimi belirli kullanıcılarla kısıtlamak için bir oluşturucu aşırı yüklemesi kullanabilir veya SemaphoreAcl adlandırılmış semaforu oluştururken bir SemaphoreSecurity geçirebilirsiniz. Kod çalıştıran güvenilmeyen kullanıcıların olabileceği sistemlerde erişim kısıtlamaları olmadan adlandırılmış semafor kullanmaktan kaçının.

Ayrıca bkz.

Şunlara uygulanır

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

sınıfının yeni bir örneğini Semaphore başlatır, ilk girdi sayısını ve en fazla eşzamanlı girdi sayısını belirtir, isteğe bağlı olarak sistem semafor nesnesinin adını belirtir, yeni bir sistem semaforunun oluşturulup oluşturulmadığını belirten bir değer alan bir değişken belirtir ve sistem semaforu için güvenlik erişim denetimi belirtir.

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)

Parametreler

initialCount
Int32

Semafor için eşzamanlı olarak karşılanabilecek ilk istek sayısı.

maximumCount
Int32

Semafor için eşzamanlı olarak karşılanabilecek en fazla istek sayısı.

name
String

Eşitleme nesnesi diğer işlemlerle paylaşılacaksa adı; null veya boş bir dize. Bu ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde ad alanı dışladıktan sonra adın geçerli bir dosya adı olması gerekir.

createdNew
Boolean

Bu yöntem döndürdüğünde, yerel bir semafor oluşturulup oluşturulmadığını (varsa nullname veya boş bir dize) veya belirtilen adlandırılmış sistem semaforunun oluşturulup oluşturulmadığını; false belirtilen adlandırılmış sistem semaforunun zaten mevcut olup olmadığını içerirtrue. Bu parametre, başlatmadan iletilir.

semaphoreSecurity
SemaphoreSecurity

SemaphoreSecurity Adlandırılmış sistem semafora uygulanacak erişim denetimi güvenliğini temsil eden bir nesne.

Özel durumlar

initialCount değerinden büyüktür maximumCount.

-veya-

Yalnızca .NET Framework: name MAX_PATH(260 karakter) uzundur.

maximumCount 1'den küçüktür.

-veya-

initialCount 0'dan küçüktür.

Adlandırılmış semafor var ve erişim denetimi güvenliğine sahip ve kullanıcının yok FullControl.

name geçersizdir. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilen bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve ortak ön eklerin "Genel\" ve "Yerel\" büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. Özelliği HResult daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz . Nesne Adları .

name Çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.

Örnekler

Aşağıdaki kod örneği, erişim denetimi güvenliğine sahip adlandırılmış bir semaforun işlemler arası davranışını gösterir. Örnek, adlandırılmış bir semaforun varlığını test etmek için yöntem aşırı yüklemesini kullanır OpenExisting(String) . Semafor yoksa, en fazla iki sayıyla ve geçerli kullanıcıya semafor kullanma hakkını reddeden ancak semafor üzerinde okuma ve değiştirme izinleri veren erişim denetimi güvenliğiyle oluşturulur. Derlenmiş örneği iki komut penceresi üzerinden çalıştırırsanız, ikinci kopya yöntem çağrısında OpenExisting(String) bir erişim ihlali özel durumu oluşturur. Özel durum yakalanmış ve örnek, izinleri okumak ve değiştirmek için gereken haklarla semaforu açmak için yöntem aşırı yüklemesini kullanır OpenExisting(String, SemaphoreRights) .

İzinler değiştirildikten sonra, semafor girmek ve serbest bırakmak için gereken haklarla açılır. Derlenmiş örneği üçüncü bir komut penceresinden çalıştırırsanız, yeni izinler kullanılarak çalıştırılır.

#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

Açıklamalar

Bu oluşturucuyu, adlandırılmış bir sistem semaforu oluşturulduğunda erişim denetimi güvenliğini uygulamak ve diğer kodun semaforun denetimini almasını engellemek için kullanın.

name bir ad alanı belirtmek için veya Local\ ön ekine Global\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows'da oturum bir oturum açma oturumudur ve hizmetler genellikle farklı bir etkileşimli olmayan oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, tümü aynı oturumda çalıştırıldığı bir üst/alt ilişki ile işlemler arasında eşitleme için uygun olabilir. Windows'da eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Nesne Adları.

bir name sağlanırsa ve istenen türdeki bir eşitleme nesnesi ad alanında zaten varsa, mevcut eşitleme nesnesi kullanılır. Ad alanında farklı türde bir eşitleme nesnesi zaten varsa, bir WaitHandleCannotBeOpenedException oluşturulur. Aksi takdirde, yeni bir eşitleme nesnesi oluşturulur.

Bu oluşturucu, adlandırılmış bir Semaphore sistem semaforu temsil eden bir nesne başlatır. Aynı adlandırılmış sistem semaforunu temsil eden birden çok Semaphore nesne oluşturabilirsiniz.

Adlandırılmış sistem semaforu yoksa, belirtilen erişim denetimi güvenliğiyle oluşturulur. Adlandırılmış semafor varsa, belirtilen erişim denetimi güvenliği yoksayılır.

Not

Çağıran, geçerli kullanıcıya bazı erişim hakları vermeyi reddetse veya veremediğinde semaphoreSecurity bile yeni oluşturulan Semaphore nesne üzerinde tam denetime sahiptir. Ancak, geçerli kullanıcı bir oluşturucu veya OpenExisting yöntem kullanarak aynı adlandırılmış semaforu temsil eden başka Semaphore bir nesne almaya çalışırsa, Windows erişim denetimi güvenliği uygulanır.

Adlandırılmış sistem semaforu yoksa, ve maximumCounttarafından initialCount belirtilen ilk sayı ve maksimum sayı ile oluşturulur. Adlandırılmış sistem semaforu zaten varsa initialCount ve maximumCount kullanılmıyorsa, ancak geçersiz değerler yine de özel durumlara neden olur. Sistem semaforunun createdNew bu oluşturucu tarafından oluşturulup oluşturulmadığını belirlemek için parametresini kullanın.

değerinden küçükse ve ise, etki, geçerli iş parçacığının (maximumCount eksi initialCount) kez çağrılmış WaitOne olmasıyla aynıdır.truecreatedNewinitialCountmaximumCount

için veya için nameboş bir dize belirtirseniznull, oluşturucu aşırı yüklemesini Semaphore(Int32, Int32) çağırmış gibi yerel bir semafor oluşturulur. Bu durumda, createdNew her zaman trueolur.

Adlandırılmış semaforlar işletim sistemi genelinde görünür olduğundan, işlem sınırları arasında kaynak kullanımını koordine etmek için kullanılabilirler.

Dikkat

Varsayılan olarak, adlandırılmış bir semafor onu oluşturan kullanıcıyla sınırlı değildir. Semaforu birden çok kez alarak ve serbest bırakmayarak semafora müdahale etmek de dahil olmak üzere diğer kullanıcılar semaforu açabilir ve kullanabilir. Belirli kullanıcılara erişimi kısıtlamak için, adlandırılmış semaforu oluştururken bir SemaphoreSecurity geçirebilirsiniz. Kod çalıştıran güvenilmeyen kullanıcıların olabileceği sistemlerde erişim kısıtlamaları olmadan adlandırılmış semafor kullanmaktan kaçının.

Ayrıca bkz.

Şunlara uygulanır