Share via


Semaphore Konstruktor

Definisi

Menginisialisasi instans baru kelas Semaphore.

Overload

Semaphore(Int32, Int32)

Menginisialisasi instans Semaphore baru kelas, menentukan jumlah awal entri dan jumlah maksimum entri bersamaan.

Semaphore(Int32, Int32, String)

Menginisialisasi instans Semaphore baru kelas, menentukan jumlah awal entri dan jumlah maksimum entri bersamaan, dan secara opsional menentukan nama objek semaphore sistem.

Semaphore(Int32, Int32, String, Boolean)

Menginisialisasi instans Semaphore baru kelas, menentukan jumlah awal entri dan jumlah maksimum entri bersamaan, secara opsional menentukan nama objek semaphore sistem, dan menentukan variabel yang menerima nilai yang menunjukkan apakah semaphore sistem baru dibuat.

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

Menginisialisasi instans Semaphore baru kelas, menentukan jumlah awal entri dan jumlah maksimum entri bersamaan, secara opsional menentukan nama objek semaphore sistem, menentukan variabel yang menerima nilai yang menunjukkan apakah semaphore sistem baru dibuat, dan menentukan kontrol akses keamanan untuk semaphore sistem.

Semaphore(Int32, Int32)

Sumber:
Semaphore.cs
Sumber:
Semaphore.cs
Sumber:
Semaphore.cs

Menginisialisasi instans Semaphore baru kelas, menentukan jumlah awal entri dan jumlah maksimum entri bersamaan.

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)

Parameter

initialCount
Int32

Jumlah awal permintaan untuk semaphore yang dapat diberikan secara bersamaan.

maximumCount
Int32

Jumlah maksimum permintaan untuk semaphore yang dapat diberikan secara bersamaan.

Pengecualian

initialCount lebih besar dari maximumCount.

maximumCount kurang dari 1.

-atau-

initialCount kurang dari 0.

Contoh

Contoh berikut membuat semaphore dengan jumlah maksimum tiga dan jumlah awal nol. Contohnya memulai lima utas, yang memblokir menunggu semaphore. Utas Release(Int32) utama menggunakan metode kelebihan beban untuk meningkatkan jumlah semaphore hingga maksimumnya, memungkinkan tiga utas memasuki semaphore. Setiap utas Thread.Sleep menggunakan metode untuk menunggu satu detik, untuk mensimulasikan pekerjaan, lalu memanggil Release() metode kelebihan beban untuk melepaskan semaphore. Setiap kali semaphore dirilis, jumlah semaphore sebelumnya ditampilkan. Pesan konsol melacak penggunaan semaphore. Interval kerja yang disimulasikan sedikit ditingkatkan untuk setiap utas, untuk membuat output lebih mudah dibaca.

#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

Keterangan

Konstruktor ini menginisialisasi semaphore yang tidak disebutkan namanya. Semua utas yang menggunakan instans semaphore tersebut harus memiliki referensi ke instans.

Jika initialCount kurang dari maximumCount, efeknya sama seperti jika utas saat ini telah memanggil WaitOne (maximumCount minus initialCount) kali. Jika Anda tidak ingin memesan entri apa pun untuk utas yang membuat semaphore, gunakan angka yang sama untuk maximumCount dan initialCount.

Lihat juga

Berlaku untuk

Semaphore(Int32, Int32, String)

Sumber:
Semaphore.cs
Sumber:
Semaphore.cs
Sumber:
Semaphore.cs

Menginisialisasi instans Semaphore baru kelas, menentukan jumlah awal entri dan jumlah maksimum entri bersamaan, dan secara opsional menentukan nama objek semaphore sistem.

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)

Parameter

initialCount
Int32

Jumlah awal permintaan untuk semaphore yang dapat diberikan secara bersamaan.

maximumCount
Int32

Jumlah maksimum permintaan untuk semaphore yang dapat diberikan secara bersamaan.

name
String

Nama, jika objek sinkronisasi akan dibagikan dengan proses lain; jika tidak, null atau string kosong. Namanya peka huruf besar/kecil. Karakter garis miring terbalik (\) dicadangkan dan hanya dapat digunakan untuk menentukan namespace layanan. Untuk informasi selengkapnya tentang namespace layanan, lihat bagian keterangan. Mungkin ada pembatasan lebih lanjut pada nama tergantung pada sistem operasi. Misalnya, pada sistem operasi berbasis Unix, nama setelah mengecualikan namespace harus berupa nama file yang valid.

Pengecualian

initialCount lebih besar dari maximumCount.

-atau-

.NET Framework saja: name lebih panjang dari MAX_PATH (260 karakter).

maximumCount kurang dari 1.

-atau-

initialCount kurang dari 0.

name tidak valid. Ini bisa karena berbagai alasan, termasuk beberapa batasan yang mungkin ditempatkan oleh sistem operasi, seperti awalan yang tidak diketahui atau karakter yang tidak valid. Perhatikan bahwa nama dan awalan umum "Global\" dan "Local\" peka huruf besar/kecil.

-atau-

Ada beberapa kesalahan lainnya. Properti HResult dapat memberikan informasi lebih lanjut.

Hanya Windows: name menentukan namespace yang tidak dikenal. Lihat Nama Objek untuk informasi selengkapnya.

Terlalu name panjang. Pembatasan panjang dapat bergantung pada sistem operasi atau konfigurasi.

Semaphore bernama ada dan memiliki keamanan kontrol akses, dan pengguna tidak memiliki FullControl.

Objek sinkronisasi dengan yang disediakan name tidak dapat dibuat. Objek sinkronisasi dari jenis yang berbeda mungkin memiliki nama yang sama.

Contoh

Contoh kode berikut menunjukkan perilaku lintas proses dari semaphore bernama. Contohnya membuat semaphore bernama dengan jumlah maksimum lima dan jumlah awal lima. Program ini melakukan tiga panggilan ke WaitOne metode . Dengan demikian, jika Anda menjalankan contoh yang dikompilasi dari dua jendela perintah, salinan kedua akan memblokir pada panggilan ketiga ke WaitOne. Lepaskan satu atau beberapa entri dalam salinan pertama program untuk membuka blokir yang kedua.

#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

Keterangan

Konstruktor ini menginisialisasi Semaphore objek yang mewakili semaphore sistem bernama. Anda dapat membuat beberapa Semaphore objek yang mewakili semaphore sistem bernama yang sama.

name mungkin diawali dengan Global\ atau Local\ untuk menentukan namespace. Global Ketika namespace ditentukan, objek sinkronisasi dapat dibagikan dengan proses apa pun pada sistem. Local Ketika namespace ditentukan, yang juga merupakan default ketika tidak ada namespace yang ditentukan, objek sinkronisasi dapat dibagikan dengan proses dalam sesi yang sama. Di Windows, sesi adalah sesi masuk, dan layanan biasanya berjalan dalam sesi non-interaktif yang berbeda. Pada sistem operasi seperti Unix, setiap shell memiliki sesinya sendiri. Objek sinkronisasi sesi-lokal mungkin sesuai untuk menyinkronkan antara proses dengan hubungan induk/anak di mana semuanya berjalan dalam sesi yang sama. Untuk informasi selengkapnya tentang nama objek sinkronisasi di Windows, lihat Nama Objek.

name Jika disediakan dan objek sinkronisasi dari jenis yang diminta sudah ada di namespace layanan, objek sinkronisasi yang ada akan digunakan. Jika objek sinkronisasi dari jenis yang berbeda sudah ada di namespace layanan, WaitHandleCannotBeOpenedException akan dilemparkan. Jika tidak, objek sinkronisasi baru dibuat.

Jika semaphore sistem bernama tidak ada, itu dibuat dengan jumlah awal dan jumlah maksimum yang ditentukan oleh initialCount dan maximumCount. Jika semaphore sistem bernama sudah ada, initialCount dan maximumCount tidak digunakan, meskipun nilai yang tidak valid masih menyebabkan pengecualian. Jika Anda perlu menentukan apakah semaphore sistem bernama dibuat atau tidak, gunakan Semaphore(Int32, Int32, String, Boolean) overload konstruktor sebagai gantinya.

Penting

Ketika Anda menggunakan kelebihan beban konstruktor ini, praktik yang disarankan adalah menentukan angka yang sama untuk initialCount dan maximumCount. Jika initialCount kurang dari maximumCount, dan semaphore sistem bernama dibuat, efeknya sama seperti jika utas saat ini telah memanggil WaitOne (maximumCount minus initialCount) kali. Namun, dengan kelebihan beban konstruktor ini tidak ada cara untuk menentukan apakah semaphore sistem bernama dibuat.

Jika Anda menentukan null atau string kosong untuk name, semaphore lokal dibuat, seolah-olah Anda telah memanggil Semaphore(Int32, Int32) overload konstruktor.

Karena semaphores bernama terlihat di seluruh sistem operasi, mereka dapat digunakan untuk mengoordinasikan penggunaan sumber daya di seluruh batas proses.

Jika Anda ingin mengetahui apakah ada semaphore sistem bernama, gunakan metode .OpenExisting Metode ini OpenExisting mencoba membuka semaphore bernama yang ada, dan melemparkan pengecualian jika sistem semaphore tidak ada.

Perhatian

Secara default, semaphore bernama tidak dibatasi untuk pengguna yang membuatnya. Pengguna lain mungkin dapat membuka dan menggunakan semaphore, termasuk mengganggu semaphore dengan memperoleh semaphore beberapa kali dan tidak merilisnya. Untuk membatasi akses ke pengguna tertentu, Anda dapat menggunakan kelebihan beban konstruktor atau SemaphoreAcl dan meneruskan SemaphoreSecurity saat membuat semaphore bernama. Hindari menggunakan semaphores bernama tanpa pembatasan akses pada sistem yang mungkin memiliki pengguna yang tidak tepercaya menjalankan kode.

Lihat juga

Berlaku untuk

Semaphore(Int32, Int32, String, Boolean)

Sumber:
Semaphore.cs
Sumber:
Semaphore.cs
Sumber:
Semaphore.cs

Menginisialisasi instans Semaphore baru kelas, menentukan jumlah awal entri dan jumlah maksimum entri bersamaan, secara opsional menentukan nama objek semaphore sistem, dan menentukan variabel yang menerima nilai yang menunjukkan apakah semaphore sistem baru dibuat.

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)

Parameter

initialCount
Int32

Jumlah awal permintaan untuk semaphore yang dapat dipenuhi secara bersamaan.

maximumCount
Int32

Jumlah maksimum permintaan untuk semaphore yang dapat dipenuhi secara bersamaan.

name
String

Nama, jika objek sinkronisasi akan dibagikan dengan proses lain; jika tidak, null atau string kosong. Namanya peka huruf besar/kecil. Karakter garis miring terbalik (\) dicadangkan dan hanya dapat digunakan untuk menentukan namespace layanan. Untuk informasi selengkapnya tentang namespace layanan, lihat bagian keterangan. Mungkin ada pembatasan lebih lanjut pada nama tergantung pada sistem operasi. Misalnya, pada sistem operasi berbasis Unix, nama setelah mengecualikan namespace harus berupa nama file yang valid.

createdNew
Boolean

Ketika metode ini kembali, berisi true apakah semaphore lokal dibuat (yaitu, jika name adalah null atau string kosong) atau jika semaphore sistem bernama yang ditentukan dibuat; false jika semaphore sistem bernama yang ditentukan sudah ada. Parameter ini diteruskan tanpa diinisialisasi.

Pengecualian

initialCount lebih besar dari maximumCount.

-atau-

.NET Framework saja: name lebih panjang dari MAX_PATH (260 karakter).

maximumCount kurang dari 1.

-atau-

initialCount kurang dari 0.

name tidak valid. Ini bisa karena berbagai alasan, termasuk beberapa batasan yang mungkin ditempatkan oleh sistem operasi, seperti awalan yang tidak diketahui atau karakter yang tidak valid. Perhatikan bahwa nama dan awalan umum "Global\" dan "Local\" peka huruf besar/kecil.

-atau-

Ada beberapa kesalahan lainnya. Properti HResult dapat memberikan informasi lebih lanjut.

Hanya Windows: name menentukan namespace yang tidak dikenal. Lihat Nama Objek untuk informasi selengkapnya.

Terlalu name panjang. Pembatasan panjang dapat bergantung pada sistem operasi atau konfigurasi.

Semaphore bernama ada dan memiliki keamanan kontrol akses, dan pengguna tidak memiliki FullControl.

Objek sinkronisasi dengan yang disediakan name tidak dapat dibuat. Objek sinkronisasi dari jenis yang berbeda mungkin memiliki nama yang sama.

Contoh

Contoh kode berikut menunjukkan perilaku lintas proses dari semaphore bernama. Contohnya membuat semaphore bernama dengan jumlah maksimum lima dan jumlah awal dua. Artinya, ia mencadangkan tiga entri untuk utas yang memanggil konstruktor. Jika createNew adalah false, program melakukan tiga panggilan ke WaitOne metode . Dengan demikian, jika Anda menjalankan contoh yang dikompilasi dari dua jendela perintah, salinan kedua akan memblokir pada panggilan ketiga ke WaitOne. Lepaskan satu atau beberapa entri dalam salinan pertama program untuk membuka blokir yang kedua.

#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

Keterangan

name mungkin diawali dengan Global\ atau Local\ untuk menentukan namespace. Global Ketika namespace ditentukan, objek sinkronisasi dapat dibagikan dengan proses apa pun pada sistem. Local Ketika namespace ditentukan, yang juga merupakan default ketika tidak ada namespace yang ditentukan, objek sinkronisasi dapat dibagikan dengan proses dalam sesi yang sama. Di Windows, sesi adalah sesi masuk, dan layanan biasanya berjalan dalam sesi non-interaktif yang berbeda. Pada sistem operasi seperti Unix, setiap shell memiliki sesinya sendiri. Objek sinkronisasi sesi-lokal mungkin sesuai untuk menyinkronkan antara proses dengan hubungan induk/anak di mana semuanya berjalan dalam sesi yang sama. Untuk informasi selengkapnya tentang nama objek sinkronisasi di Windows, lihat Nama Objek.

name Jika disediakan dan objek sinkronisasi dari jenis yang diminta sudah ada di namespace layanan, objek sinkronisasi yang ada akan digunakan. Jika objek sinkronisasi dari jenis yang berbeda sudah ada di namespace layanan, WaitHandleCannotBeOpenedException akan dilemparkan. Jika tidak, objek sinkronisasi baru dibuat.

Konstruktor ini menginisialisasi Semaphore objek yang mewakili semaphore sistem bernama. Anda dapat membuat beberapa Semaphore objek yang mewakili semaphore sistem bernama yang sama.

Jika semaphore sistem bernama tidak ada, itu dibuat dengan jumlah awal dan jumlah maksimum yang ditentukan oleh initialCount dan maximumCount. Jika semaphore sistem bernama sudah ada, initialCount dan maximumCount tidak digunakan, meskipun nilai yang tidak valid masih menyebabkan pengecualian. Gunakan createdNew untuk menentukan apakah semaphore sistem dibuat.

Jika initialCount kurang dari maximumCount, dan createdNew adalah true, efeknya sama seperti jika utas saat ini telah memanggil WaitOne (maximumCount minus initialCount) kali.

Jika Anda menentukan null atau string kosong untuk name, semaphore lokal dibuat, seolah-olah Anda telah memanggil Semaphore(Int32, Int32) overload konstruktor. Dalam hal ini, createdNew selalu true.

Karena semaphores bernama terlihat di seluruh sistem operasi, mereka dapat digunakan untuk mengoordinasikan penggunaan sumber daya di seluruh batas proses.

Perhatian

Secara default, semaphore bernama tidak dibatasi untuk pengguna yang membuatnya. Pengguna lain mungkin dapat membuka dan menggunakan semaphore, termasuk mengganggu semaphore dengan memperoleh semaphore beberapa kali dan tidak merilisnya. Untuk membatasi akses ke pengguna tertentu, Anda dapat menggunakan kelebihan beban konstruktor atau SemaphoreAcl dan meneruskan SemaphoreSecurity saat membuat semaphore bernama. Hindari menggunakan semaphores bernama tanpa pembatasan akses pada sistem yang mungkin memiliki pengguna yang tidak tepercaya menjalankan kode.

Lihat juga

Berlaku untuk

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

Menginisialisasi instans Semaphore baru kelas , menentukan jumlah awal entri dan jumlah maksimum entri bersamaan, secara opsional menentukan nama objek semaphore sistem, menentukan variabel yang menerima nilai yang menunjukkan apakah semaphore sistem baru dibuat, dan menentukan kontrol akses keamanan untuk semaphore sistem.

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)

Parameter

initialCount
Int32

Jumlah awal permintaan untuk semaphore yang dapat dipenuhi secara bersamaan.

maximumCount
Int32

Jumlah maksimum permintaan untuk semaphore yang dapat dipenuhi secara bersamaan.

name
String

Nama, jika objek sinkronisasi akan dibagikan dengan proses lain; jika tidak, null atau string kosong. Namanya peka huruf besar/kecil. Karakter garis miring terbalik (\) dicadangkan dan hanya dapat digunakan untuk menentukan namespace layanan. Untuk informasi selengkapnya tentang namespace layanan, lihat bagian keterangan. Mungkin ada pembatasan lebih lanjut pada nama tergantung pada sistem operasi. Misalnya, pada sistem operasi berbasis Unix, nama setelah mengecualikan namespace harus berupa nama file yang valid.

createdNew
Boolean

Ketika metode ini kembali, berisi true apakah semaphore lokal dibuat (yaitu, jika name adalah null atau string kosong) atau jika semaphore sistem bernama yang ditentukan dibuat; false jika semaphore sistem bernama yang ditentukan sudah ada. Parameter ini diteruskan tanpa diinisialisasi.

semaphoreSecurity
SemaphoreSecurity

Objek SemaphoreSecurity yang mewakili keamanan kontrol akses yang akan diterapkan ke semaphore sistem bernama.

Pengecualian

initialCount lebih besar dari maximumCount.

-atau-

.NET Framework saja: name lebih panjang dari MAX_PATH (260 karakter).

maximumCount kurang dari 1.

-atau-

initialCount kurang dari 0.

Semaphore bernama ada dan memiliki keamanan kontrol akses, dan pengguna tidak memiliki FullControl.

name tidak valid. Ini bisa karena berbagai alasan, termasuk beberapa batasan yang mungkin ditempatkan oleh sistem operasi, seperti awalan yang tidak diketahui atau karakter yang tidak valid. Perhatikan bahwa nama dan awalan umum "Global\" dan "Local\" peka huruf besar/kecil.

-atau-

Ada beberapa kesalahan lainnya. Properti HResult dapat memberikan informasi lebih lanjut.

Hanya Windows: name menentukan namespace yang tidak dikenal. Lihat Nama Objek untuk informasi selengkapnya.

Terlalu name panjang. Pembatasan panjang dapat bergantung pada sistem operasi atau konfigurasi.

Objek sinkronisasi dengan yang disediakan name tidak dapat dibuat. Objek sinkronisasi dari jenis yang berbeda mungkin memiliki nama yang sama.

Contoh

Contoh kode berikut menunjukkan perilaku lintas proses dari semaphore bernama dengan keamanan kontrol akses. Contohnya menggunakan OpenExisting(String) metode kelebihan beban untuk menguji keberadaan semaphore bernama. Jika semaphore tidak ada, itu dibuat dengan jumlah maksimum dua dan dengan keamanan kontrol akses yang menolak pengguna saat ini hak untuk menggunakan semaphore tetapi memberikan hak untuk membaca dan mengubah izin pada semaphore. Jika Anda menjalankan contoh yang dikompilasi dari dua jendela perintah, salinan kedua akan melemparkan pengecualian pelanggaran akses pada panggilan ke OpenExisting(String) metode . Pengecualian tertangkap, dan contohnya menggunakan OpenExisting(String, SemaphoreRights) metode kelebihan beban untuk membuka semaphore dengan hak yang diperlukan untuk membaca dan mengubah izin.

Setelah izin diubah, semaphore dibuka dengan hak yang diperlukan untuk memasukkan dan melepaskan. Jika Anda menjalankan contoh yang dikompilasi dari jendela perintah ketiga, contoh tersebut berjalan menggunakan izin baru.

#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

Keterangan

Gunakan konstruktor ini untuk menerapkan keamanan kontrol akses ke semaphore sistem bernama saat dibuat, mencegah kode lain mengendalikan semaphore.

name mungkin diawali dengan Global\ atau Local\ untuk menentukan namespace. Global Ketika namespace ditentukan, objek sinkronisasi dapat dibagikan dengan proses apa pun pada sistem. Local Ketika namespace ditentukan, yang juga merupakan default ketika tidak ada namespace yang ditentukan, objek sinkronisasi dapat dibagikan dengan proses dalam sesi yang sama. Di Windows, sesi adalah sesi masuk, dan layanan biasanya berjalan dalam sesi non-interaktif yang berbeda. Pada sistem operasi seperti Unix, setiap shell memiliki sesinya sendiri. Objek sinkronisasi sesi-lokal mungkin sesuai untuk disinkronkan antara proses dengan hubungan induk/anak di mana semuanya berjalan dalam sesi yang sama. Untuk informasi selengkapnya tentang nama objek sinkronisasi di Windows, lihat Nama Objek.

name Jika disediakan dan objek sinkronisasi dari jenis yang diminta sudah ada di namespace layanan, objek sinkronisasi yang ada akan digunakan. Jika objek sinkronisasi dari jenis yang berbeda sudah ada di namespace, akan WaitHandleCannotBeOpenedException dilemparkan. Jika tidak, objek sinkronisasi baru dibuat.

Konstruktor ini menginisialisasi Semaphore objek yang mewakili semaphore sistem bernama. Anda dapat membuat beberapa Semaphore objek yang mewakili semaphore sistem bernama yang sama.

Jika semaphore sistem bernama tidak ada, itu dibuat dengan keamanan kontrol akses yang ditentukan. Jika semaphore bernama ada, keamanan kontrol akses yang ditentukan akan diabaikan.

Catatan

Pemanggil memiliki kontrol penuh atas objek yang baru dibuat Semaphore meskipun semaphoreSecurity menolak atau gagal memberikan beberapa hak akses kepada pengguna saat ini. Namun, jika pengguna saat ini mencoba mendapatkan objek lain Semaphore untuk mewakili semaphore bernama yang sama, menggunakan konstruktor atau OpenExisting metode , keamanan kontrol akses Windows diterapkan.

Jika semaphore sistem bernama tidak ada, itu dibuat dengan jumlah awal dan jumlah maksimum yang ditentukan oleh initialCount dan maximumCount. Jika semaphore sistem bernama sudah ada, initialCount dan maximumCount tidak digunakan, meskipun nilai yang tidak valid masih menyebabkan pengecualian. createdNew Gunakan parameter untuk menentukan apakah semaphore sistem dibuat oleh konstruktor ini.

Jika initialCount kurang dari maximumCount, dan createdNew adalah true, efeknya sama seperti jika utas saat ini telah memanggil WaitOne (maximumCount minus initialCount) kali.

Jika Anda menentukan null atau string kosong untuk name, semaphore lokal dibuat, seolah-olah Anda telah memanggil Semaphore(Int32, Int32) overload konstruktor. Dalam hal ini, createdNew selalu true.

Karena bernama semaphores terlihat di seluruh sistem operasi, mereka dapat digunakan untuk mengoordinasikan penggunaan sumber daya di seluruh batas proses.

Perhatian

Secara default, semaphore bernama tidak dibatasi untuk pengguna yang membuatnya. Pengguna lain mungkin dapat membuka dan menggunakan semaphore, termasuk mengganggu semaphore dengan memperoleh semaphore beberapa kali dan tidak merilisnya. Untuk membatasi akses ke pengguna tertentu, Anda dapat meneruskan SemaphoreSecurity saat membuat semaphore bernama. Hindari menggunakan semaphores bernama tanpa pembatasan akses pada sistem yang mungkin memiliki pengguna yang tidak tepercaya yang menjalankan kode.

Lihat juga

Berlaku untuk