Semaphore.Release Método

Definição

Sai do semáforo.

Sobrecargas

Nome Description
Release()

Sai do semáforo e retorna a contagem anterior.

Release(Int32)

Sai do semáforo um número especificado de vezes e retorna a contagem anterior.

Release()

Origem:
Semaphore.cs
Origem:
Semaphore.cs
Origem:
Semaphore.cs
Origem:
Semaphore.cs
Origem:
Semaphore.cs

Sai do semáforo e retorna a contagem anterior.

public:
 int Release();
public int Release();
member this.Release : unit -> int
Public Function Release () As Integer

Retornos

A contagem no semáforo antes do Release método ser chamado.

Exceções

A contagem de semáforos já está no valor máximo.

Ocorreu um erro win32 com um semáforo nomeado.

O semáforo atual representa um semáforo do sistema nomeado, mas o usuário não tem Modify.

- ou -

O semáforo atual representa um semáforo do sistema nomeado, mas não foi aberto com Modify.

Exemplos

O exemplo de código a seguir cria um semáforo com uma contagem máxima de três e uma contagem inicial de zero. O exemplo inicia cinco threads, que bloqueiam a espera pelo semáforo. O thread principal usa a sobrecarga do Release(Int32) método para aumentar a contagem de semáforos para o máximo, permitindo que três threads insiram o semáforo. Cada thread usa o Thread.Sleep método para aguardar um segundo, simular o trabalho e, em seguida, chama a sobrecarga do Release() método para liberar o semáforo.

Cada vez que o semáforo é liberado, a contagem de semáforos anterior é exibida. As mensagens de console rastreiam o uso de semáforo. O intervalo de trabalho simulado é aumentado ligeiramente para cada thread, para facilitar a leitura da saída.

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

Comentários

Os threads normalmente usam o WaitOne método para inserir o semáforo e normalmente usam essa sobrecarga de método para sair.

Se um SemaphoreFullException for gerado pelo Release método, ele não indicará necessariamente um problema com o thread de chamada. Um erro de programação em outro thread pode ter feito com que esse thread saísse do semáforo mais vezes do que ele inseriu.

Se o objeto atual Semaphore representa um semáforo do sistema nomeado, o usuário deve ter SemaphoreRights.Modify direitos e o semáforo deve ter sido aberto com SemaphoreRights.Modify direitos.

Confira também

Aplica-se a

Release(Int32)

Origem:
Semaphore.cs
Origem:
Semaphore.cs
Origem:
Semaphore.cs
Origem:
Semaphore.cs
Origem:
Semaphore.cs

Sai do semáforo um número especificado de vezes e retorna a contagem anterior.

public:
 int Release(int releaseCount);
public int Release(int releaseCount);
member this.Release : int -> int
Public Function Release (releaseCount As Integer) As Integer

Parâmetros

releaseCount
Int32

O número de vezes para sair do semáforo.

Retornos

A contagem no semáforo antes do Release método ser chamado.

Exceções

releaseCount é menor que 1.

A contagem de semáforos já está no valor máximo.

Ocorreu um erro win32 com um semáforo nomeado.

O semáforo atual representa um semáforo do sistema nomeado, mas o usuário não tem Modify direitos.

- ou -

O semáforo atual representa um semáforo do sistema nomeado, mas não foi aberto com Modify direitos.

Exemplos

O exemplo de código a seguir cria um semáforo com uma contagem máxima de três e uma contagem inicial de zero. O exemplo inicia cinco threads, que bloqueiam a espera pelo semáforo. O thread principal usa a sobrecarga do Release(Int32) método para aumentar a contagem de semáforos para o máximo, permitindo que três threads insiram o semáforo. Cada thread usa o Thread.Sleep método para aguardar um segundo, simular o trabalho e, em seguida, chama a sobrecarga do Release() método para liberar o semáforo.

Cada vez que o semáforo é liberado, a contagem de semáforos anterior é exibida. As mensagens de console rastreiam o uso de semáforo. O intervalo de trabalho simulado é aumentado ligeiramente para cada thread, para facilitar a leitura da saída.

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

Comentários

Se um thread tiver inserido o semáforo várias vezes, essa sobrecarga de método permitirá que toda a contagem de semáforos seja restaurada com uma chamada.

Se um SemaphoreFullException for gerado pelo Release método, ele não indicará necessariamente um problema com o thread de chamada. Um erro de programação em outro thread pode ter feito com que esse thread saísse do semáforo mais vezes do que ele inseriu.

Se o objeto atual Semaphore representa um semáforo do sistema nomeado, o usuário deve ter SemaphoreRights.Modify direitos e o semáforo deve ter sido aberto com SemaphoreRights.Modify direitos.

Confira também

Aplica-se a