Bagikan melalui


SemaphoreSlim Kelas

Definisi

Mewakili alternatif ringan untuk Semaphore yang membatasi jumlah utas yang dapat mengakses sumber daya atau kumpulan sumber daya secara bersamaan.

public ref class SemaphoreSlim : IDisposable
public class SemaphoreSlim : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class SemaphoreSlim : IDisposable
type SemaphoreSlim = class
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(false)>]
type SemaphoreSlim = class
    interface IDisposable
Public Class SemaphoreSlim
Implements IDisposable
Warisan
SemaphoreSlim
Atribut
Penerapan

Contoh

Contoh berikut membuat semaphore dengan jumlah maksimum tiga utas dan jumlah awal nol utas. Contohnya memulai lima tugas, yang semuanya memblokir menunggu semaphore. Utas Release(Int32) utama memanggil kelebihan beban untuk meningkatkan jumlah semaphore hingga maksimum, yang memungkinkan tiga tugas untuk memasuki 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;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
    private static SemaphoreSlim semaphore;
    // A padding interval to make the output more orderly.
    private static int padding;

    public static void Main()
    {
        // Create the semaphore.
        semaphore = new SemaphoreSlim(0, 3);
        Console.WriteLine("{0} tasks can enter the semaphore.",
                          semaphore.CurrentCount);
        Task[] tasks = new Task[5];

        // Create and start five numbered tasks.
        for (int i = 0; i <= 4; i++)
        {
            tasks[i] = Task.Run(() =>
            {
                // Each task begins by requesting the semaphore.
                Console.WriteLine("Task {0} begins and waits for the semaphore.",
                                  Task.CurrentId);
                
                int semaphoreCount;
                semaphore.Wait();
                try
                {
                    Interlocked.Add(ref padding, 100);

                    Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId);

                    // The task just sleeps for 1+ seconds.
                    Thread.Sleep(1000 + padding);
                }
                finally {
                    semaphoreCount = semaphore.Release();
                }
                Console.WriteLine("Task {0} releases the semaphore; previous count: {1}.",
                                  Task.CurrentId, semaphoreCount);
            });
        }

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

        // Restore the semaphore count to its maximum value.
        Console.Write("Main thread calls Release(3) --> ");
        semaphore.Release(3);
        Console.WriteLine("{0} tasks can enter the semaphore.",
                          semaphore.CurrentCount);
        // Main thread waits for the tasks to complete.
        Task.WaitAll(tasks);

        Console.WriteLine("Main thread exits.");
    }
}
// The example displays output like the following:
//       0 tasks can enter the semaphore.
//       Task 1 begins and waits for the semaphore.
//       Task 5 begins and waits for the semaphore.
//       Task 2 begins and waits for the semaphore.
//       Task 4 begins and waits for the semaphore.
//       Task 3 begins and waits for the semaphore.
//       Main thread calls Release(3) --> 3 tasks can enter the semaphore.
//       Task 4 enters the semaphore.
//       Task 1 enters the semaphore.
//       Task 3 enters the semaphore.
//       Task 4 releases the semaphore; previous count: 0.
//       Task 2 enters the semaphore.
//       Task 1 releases the semaphore; previous count: 0.
//       Task 3 releases the semaphore; previous count: 0.
//       Task 5 enters the semaphore.
//       Task 2 releases the semaphore; previous count: 1.
//       Task 5 releases the semaphore; previous count: 2.
//       Main thread exits.
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Private semaphore As SemaphoreSlim
    ' A padding interval to make the output more orderly.
    Private padding As Integer

   Public Sub Main()
      ' Create the semaphore.
      semaphore = New SemaphoreSlim(0, 3)
      Console.WriteLine("{0} tasks can enter the semaphore.",
                        semaphore.CurrentCount)
      Dim tasks(4) As Task

      ' Create and start five numbered tasks.
      For i As Integer = 0 To 4
         tasks(i) = Task.Run(
            Sub()
               ' Each task begins by requesting the semaphore.
               Console.WriteLine("Task {0} begins and waits for the semaphore.",
                              Task.CurrentId)
               semaphore.Wait()

               Interlocked.Add(padding, 100)

               Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId)

               ' The task just sleeps for 1+ seconds.
               Thread.Sleep(1000 + padding)

               Console.WriteLine("Task {0} releases the semaphore previous count: {1}.",
                                 Task.CurrentId, semaphore.Release())
            End Sub )
      Next

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

      ' Restore the semaphore count to its maximum value.
      Console.Write("Main thread calls Release(3) --> ")
      semaphore.Release(3)
      Console.WriteLine("{0} tasks can enter the semaphore.",
                        semaphore.CurrentCount)
      ' Main thread waits for the tasks to complete.
      Task.WaitAll(tasks)

      Console.WriteLine("Main thread exits.")
   End Sub
End Module
' The example displays output like the following:
'       0 tasks can enter the semaphore.
'       Task 1 begins and waits for the semaphore.
'       Task 5 begins and waits for the semaphore.
'       Task 2 begins and waits for the semaphore.
'       Task 4 begins and waits for the semaphore.
'       Task 3 begins and waits for the semaphore.
'       Main thread calls Release(3) --> 3 tasks can enter the semaphore.
'       Task 4 enters the semaphore.
'       Task 1 enters the semaphore.
'       Task 3 enters the semaphore.
'       Task 4 releases the semaphore; previous count: 0.
'       Task 2 enters the semaphore.
'       Task 1 releases the semaphore; previous count: 0.
'       Task 3 releases the semaphore; previous count: 0.
'       Task 5 enters the semaphore.
'       Task 2 releases the semaphore; previous count: 1.
'       Task 5 releases the semaphore; previous count: 2.
'       Main thread exits.

Keterangan

Semaphores terdiri dari dua jenis: semaphores lokal dan bernama semaphores sistem. Semaphores lokal adalah lokal untuk aplikasi, semaphores sistem terlihat di seluruh sistem operasi dan cocok untuk sinkronisasi antar-proses. SemaphoreSlim adalah alternatif ringan untuk Semaphore kelas yang tidak menggunakan semaphore kernel Windows. Semaphore Tidak seperti kelas , SemaphoreSlim kelas tidak mendukung semaphores sistem bernama. Anda dapat menggunakannya sebagai semaphore lokal saja. Kelas SemaphoreSlim ini adalah semaphore yang direkomendasikan untuk sinkronisasi dalam satu aplikasi.

Semaphore ringan mengontrol akses ke kumpulan sumber daya yang lokal untuk aplikasi Anda. Saat Anda membuat semaphore, Anda dapat menentukan jumlah maksimum utas yang dapat memasukkan semaphore secara bersamaan. Anda juga menentukan jumlah awal utas yang dapat memasukkan semaphore secara bersamaan. Ini mendefinisikan jumlah semaphore.

Jumlah direkrementasi setiap kali utas memasuki semaphore, dan bertambah setiap kali utas merilis semaphore. Untuk memasukkan semaphore, utas memanggil salah Wait satu atau WaitAsync kelebihan beban. Untuk melepaskan semaphore, ia memanggil salah Release satu kelebihan beban. Ketika jumlah mencapai nol, panggilan berikutnya ke salah Wait satu metode memblokir sampai utas lain melepaskan semaphore. Jika beberapa utas diblokir, tidak ada urutan yang dijamin, seperti FIFO atau LIFO, yang mengontrol kapan utas memasuki semaphore.

Struktur dasar untuk kode yang menggunakan semaphore untuk melindungi sumber daya adalah:

' Enter semaphore by calling one of the Wait or WaitAsync methods.
SemaphoreSlim.Wait()
'
' Execute code protected by the semaphore.
'
SemaphoreSlim.Release()

Ketika semua utas telah merilis semaphore, jumlahnya adalah pada nilai maksimum yang ditentukan ketika semaphore dibuat. Jumlah semaphore tersedia dari CurrentCount properti .

Penting

Kelas SemaphoreSlim tidak memberlakukan utas atau identitas tugas pada panggilan ke Waitmetode , WaitAsync, dan Release . Selain itu, jika SemaphoreSlim(Int32) konstruktor digunakan untuk membuat SemaphoreSlim instans objek, CurrentCount properti dapat meningkat di luar nilai yang ditetapkan oleh konstruktor. Programmer bertanggung jawab untuk memastikan bahwa panggilan ke Wait atau WaitAsync metode dipasangkan dengan tepat dengan panggilan ke Release metode.

Konstruktor

Nama Deskripsi
SemaphoreSlim(Int32, Int32)

Menginisialisasi instans SemaphoreSlim baru kelas, menentukan jumlah awal dan maksimum permintaan yang dapat diberikan secara bersamaan.

SemaphoreSlim(Int32)

Menginisialisasi instans SemaphoreSlim baru kelas, menentukan jumlah awal permintaan yang dapat diberikan secara bersamaan.

Properti

Nama Deskripsi
AvailableWaitHandle

Mengembalikan yang WaitHandle dapat digunakan untuk menunggu di semaphore.

CurrentCount

Mendapatkan jumlah utas yang tersisa yang dapat memasukkan SemaphoreSlim objek.

Metode

Nama Deskripsi
Dispose()

Merilis semua sumber daya yang digunakan oleh instans SemaphoreSlim kelas saat ini.

Dispose(Boolean)

Merilis sumber daya yang tidak dikelola yang digunakan oleh SemaphoreSlim, dan secara opsional merilis sumber daya terkelola.

Equals(Object)

Menentukan apakah objek yang ditentukan sama dengan objek saat ini.

(Diperoleh dari Object)
GetHashCode()

Berfungsi sebagai fungsi hash default.

(Diperoleh dari Object)
GetType()

Mendapatkan Type instans saat ini.

(Diperoleh dari Object)
MemberwiseClone()

Membuat salinan dangkal dari Objectsaat ini.

(Diperoleh dari Object)
Release()

Merilis SemaphoreSlim objek sekali.

Release(Int32)

Merilis SemaphoreSlim objek berapa kali tertentu.

ToString()

Mengembalikan string yang mewakili objek saat ini.

(Diperoleh dari Object)
Wait()

Memblokir utas saat ini hingga dapat memasukkan SemaphoreSlim.

Wait(CancellationToken)

Memblokir utas saat ini hingga dapat memasuki SemaphoreSlim, sambil mengamati CancellationToken.

Wait(Int32, CancellationToken)

Memblokir utas saat ini hingga dapat memasukkan SemaphoreSlim, menggunakan bilangan bulat bertanda tangan 32-bit yang menentukan batas waktu, sambil mengamati CancellationToken.

Wait(Int32)

Memblokir utas saat ini hingga dapat memasukkan SemaphoreSlim, menggunakan bilangan bulat bertanda tangan 32-bit yang menentukan batas waktu.

Wait(TimeSpan, CancellationToken)

Memblokir utas saat ini hingga dapat memasukkan SemaphoreSlim, menggunakan TimeSpan yang menentukan batas waktu, sambil mengamati CancellationToken.

Wait(TimeSpan)

Memblokir utas saat ini hingga dapat memasukkan SemaphoreSlim, menggunakan TimeSpan untuk menentukan batas waktu.

WaitAsync()

Secara asinkron menunggu untuk memasukkan SemaphoreSlim.

WaitAsync(CancellationToken)

Secara asinkron menunggu untuk memasuki SemaphoreSlim, sambil mengamati CancellationToken.

WaitAsync(Int32, CancellationToken)

Secara asinkron menunggu untuk memasukkan SemaphoreSlim, menggunakan bilangan bulat bertanda 32-bit untuk mengukur interval waktu, sambil mengamati CancellationToken.

WaitAsync(Int32)

Secara asinkron menunggu untuk memasukkan SemaphoreSlim, menggunakan bilangan bulat bertanda tangan 32-bit untuk mengukur interval waktu.

WaitAsync(TimeSpan, CancellationToken)

Secara asinkron menunggu untuk memasukkan SemaphoreSlim, menggunakan TimeSpan untuk mengukur interval waktu, sambil mengamati CancellationToken.

WaitAsync(TimeSpan)

Secara asinkron menunggu untuk memasukkan SemaphoreSlim, menggunakan TimeSpan untuk mengukur interval waktu.

Berlaku untuk

Keamanan Thread

Semua anggota SemaphoreSlim publik dan terlindungi aman utas dan dapat digunakan secara bersamaan dari beberapa utas, dengan pengecualian Dispose(), yang harus digunakan hanya ketika semua operasi lain pada SemaphoreSlim telah selesai.

Lihat juga