SemaphoreFullException SemaphoreFullException SemaphoreFullException SemaphoreFullException Class

Definição

A exceção que é lançada quando o método Release é chamado em um semáforo cuja contagem já está no máximo.The exception that is thrown when the Release method is called on a semaphore whose count is already at the maximum.

public ref class SemaphoreFullException : SystemException
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class SemaphoreFullException : SystemException
type SemaphoreFullException = class
    inherit SystemException
Public Class SemaphoreFullException
Inherits SystemException
Herança
SemaphoreFullExceptionSemaphoreFullExceptionSemaphoreFullExceptionSemaphoreFullException
Atributos

Exemplos

O exemplo de código a seguir mostra como um erro de programação em um thread pode levar a um SemaphoreFullException em outro thread: Dois threads de inserir um sinal.The following code example shows how a programming error in one thread can lead to a SemaphoreFullException in another thread: Two threads enter a semaphore. O segundo thread libera o semaphore duas vezes, enquanto o primeiro thread ainda está executando sua tarefa.The second thread releases the semaphore twice, while the first thread is still executing its task. Quando o primeiro thread termine e libere o semaphore, a contagem de semáforo já está completa e uma exceção será lançada.When the first thread finishes and releases the semaphore, the semaphore count is already full and an exception is thrown.

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // A semaphore that can satisfy at most two concurrent
   // requests.
   //
   static Semaphore^ _pool = gcnew Semaphore( 2,2 );

public:
   static void main()
   {
      // Create and start two threads, A and B.
      //
      Thread^ tA = gcnew Thread( gcnew ThreadStart( ThreadA ) );
      tA->Start();

      Thread^ tB = gcnew Thread( gcnew ThreadStart( ThreadB ) );
      tB->Start();
   }

private:
   static void ThreadA()
   {
      // Thread A enters the semaphore and simulates a task
      // that lasts a second.
      //
      _pool->WaitOne();
      Console::WriteLine( L"Thread A entered the semaphore." );

      Thread::Sleep( 1000 );

      try
      {
         _pool->Release();
         Console::WriteLine( L"Thread A released the semaphore." );
      }
      catch ( Exception^ ex ) 
      {
         Console::WriteLine( L"Thread A: {0}", ex->Message );
      }
   }

   static void ThreadB()
   {
      // Thread B simulates a task that lasts half a second,
      // then enters the semaphore.
      //
      Thread::Sleep( 500 );

      _pool->WaitOne();
      Console::WriteLine( L"Thread B entered the semaphore." );
      
      // Due to a programming error, Thread B releases the
      // semaphore twice. To fix the program, delete one line.
      _pool->Release();
      _pool->Release();
      Console::WriteLine( L"Thread B exits successfully." );
   }
};
/* This code example produces the following output:

Thread A entered the semaphore.
Thread B entered the semaphore.
Thread B exits successfully.
Thread A: Adding the given count to the semaphore would cause it to exceed its maximum count.
 */
using System;
using System.Threading;

public class Example
{
    // A semaphore that can satisfy at most two concurrent
    // requests.
    //
    private static Semaphore _pool = new Semaphore(2, 2);

    public static void Main()
    {
        // Create and start two threads, A and B. 
        //
        Thread tA = new Thread(new ThreadStart(ThreadA));
        tA.Start();

        Thread tB = new Thread(new ThreadStart(ThreadB));
        tB.Start();
    }

    private static void ThreadA()
    {
        // Thread A enters the semaphore and simulates a task
        // that lasts a second.
        //
        _pool.WaitOne();
        Console.WriteLine("Thread A entered the semaphore.");

        Thread.Sleep(1000);

        try
        {
            _pool.Release();
            Console.WriteLine("Thread A released the semaphore.");
        }
        catch(Exception ex)
        {
            Console.WriteLine("Thread A: {0}", ex.Message);
        }
    }

    private static void ThreadB()
    {
        // Thread B simulates a task that lasts half a second,
        // then enters the semaphore.
        //
        Thread.Sleep(500);

        _pool.WaitOne();
        Console.WriteLine("Thread B entered the semaphore.");
        
        // Due to a programming error, Thread B releases the
        // semaphore twice. To fix the program, delete one line.
        _pool.Release();
        _pool.Release();
        Console.WriteLine("Thread B exits successfully.");
    }
}
/* This code example produces the following output:

Thread A entered the semaphore.
Thread B entered the semaphore.
Thread B exits successfully.
Thread A: Adding the given count to the semaphore would cause it to exceed its maximum count.
 */
Imports System
Imports System.Threading

Public Class Example

    ' A semaphore that can satisfy at most two concurrent
    ' requests.
    '
    Private Shared _pool As New Semaphore(2, 2)

    <MTAThread> _
    Public Shared Sub Main()
        ' Create and start two threads, A and B. 
        '
        Dim tA As New Thread(AddressOf ThreadA)
        tA.Start()

        Dim tB As New Thread(AddressOf ThreadB)
        tB.Start()

    End Sub

    Private Shared Sub ThreadA()
        ' Thread A enters the semaphore and simulates a task
        ' that lasts a second.
        '
        _pool.WaitOne()
        Console.WriteLine("Thread A entered the semaphore.")

        Thread.Sleep(1000)

        Try
            _pool.Release()
            Console.WriteLine("Thread A released the semaphore.")
        Catch ex As Exception
            Console.WriteLine("Thread A: {0}", ex.Message)
        End Try
    End Sub

    Private Shared Sub ThreadB()
        ' Thread B simulates a task that lasts half a second,
        ' then enters the semaphore.
        '
        Thread.Sleep(500)

        _pool.WaitOne()
        Console.WriteLine("Thread B entered the semaphore.")
        
        ' Due to a programming error, Thread B releases the
        ' semaphore twice. To fix the program, delete one line.
        _pool.Release()
        _pool.Release()
        Console.WriteLine("Thread B exits successfully.")
    End Sub
End Class
' This code example produces the following output:
'
' Thread A entered the semaphore.
' Thread B entered the semaphore.
' Thread B exits successfully.
' Thread A: Adding the given count to the semaphore would cause it to exceed its maximum count.
'

Comentários

A contagem em um semáforo é decrementada sempre que um thread entra o semáforo e incrementado quando um thread libera o semaphore.The count on a semaphore is decremented each time a thread enters the semaphore, and incremented when a thread releases the semaphore. Quando a contagem for zero, as solicitações subsequentes bloqueiam até que outros threads liberam o sinal.When the count is zero, subsequent requests block until other threads release the semaphore. Quando todos os threads lançaram o semáforo, a contagem é o valor máximo especificada quando o sinal foi criado.When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created. Se um erro de programação faz com que um thread chamar o Semaphore.Release método neste ponto, um SemaphoreFullException é gerada.If a programming error causes a thread to call the Semaphore.Release method at this point, a SemaphoreFullException is thrown.

Observação

O Semaphore classe não impõe a identidade do thread em chamadas para o WaitHandle.WaitOne e Semaphore.Release métodos.The Semaphore class does not enforce thread identity on calls to the WaitHandle.WaitOne and Semaphore.Release methods. Não é necessário para o mesmo thread que chamou WaitOne chamar Release.It is not necessary for the same thread that called WaitOne to call Release.

SemaphoreFullException não indica necessariamente um problema com o código onde ocorreu a exceção.SemaphoreFullException does not necessarily indicate a problem with the code where the exception occurred. Considere o seguinte cenário: Thread B e o thread A Inserir um sinal que tem uma contagem máxima de dois.Consider the following scenario: Thread A and thread B enter a semaphore that has a maximum count of two. Um erro de programação no thread B faz com que ele chame Release duas vezes, para que a contagem no sinal está completa.A programming error in thread B causes it to call Release twice, so that the count on the semaphore is full. Como resultado, quando o thread A eventualmente chama Release, um SemaphoreFullException é gerada.As a result, when thread A eventually calls Release, a SemaphoreFullException is thrown.

Para obter uma lista de valores de propriedade inicial para uma instância das SemaphoreFullException classe, consulte o SemaphoreFullException() construtor.For a list of initial property values for an instance of the SemaphoreFullException class, see the SemaphoreFullException() constructor.

Construtores

SemaphoreFullException() SemaphoreFullException() SemaphoreFullException() SemaphoreFullException()

Inicializa uma nova instância da classe SemaphoreFullException com valores padrão.Initializes a new instance of the SemaphoreFullException class with default values.

SemaphoreFullException(SerializationInfo, StreamingContext) SemaphoreFullException(SerializationInfo, StreamingContext) SemaphoreFullException(SerializationInfo, StreamingContext) SemaphoreFullException(SerializationInfo, StreamingContext)

Inicializa uma nova instância da classe SemaphoreFullException com dados serializados.Initializes a new instance of the SemaphoreFullException class with serialized data.

SemaphoreFullException(String) SemaphoreFullException(String) SemaphoreFullException(String) SemaphoreFullException(String)

Inicializa uma nova instância da classe SemaphoreFullException com uma mensagem de erro especificada.Initializes a new instance of the SemaphoreFullException class with a specified error message.

SemaphoreFullException(String, Exception) SemaphoreFullException(String, Exception) SemaphoreFullException(String, Exception) SemaphoreFullException(String, Exception)

Inicializa uma nova instância da classe SemaphoreFullException com uma mensagem de erro especificada e uma referência à exceção interna que é a causa da exceção.Initializes a new instance of the SemaphoreFullException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Propriedades

Data Data Data Data

Obtém uma coleção de pares de chave/valor que fornecem informações adicionais definidas pelo usuário sobre a exceção.Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

Obtém ou define um link para o arquivo de ajuda associado a essa exceção.Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

Obtém ou define HRESULT, um valor numérico codificado que é atribuído a uma exceção específica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

Obtém a instância Exception que causou a exceção atual.Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message Message Message Message

Obtém uma mensagem que descreve a exceção atual.Gets a message that describes the current exception.

(Inherited from Exception)
Source Source Source Source

Obtém ou define o nome do aplicativo ou objeto que causa o erro.Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

Obtém uma representação de cadeia de caracteres de quadros imediatos na pilha de chamadas.Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

Obtém o método que gerou a exceção atual.Gets the method that throws the current exception.

(Inherited from Exception)

Métodos

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

Quando substituído em uma classe derivada, retorna a Exception que é a causa raiz de uma ou mais exceções subsequentes.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Quando substituído em uma classe derivada, define o SerializationInfo com informações sobre a exceção.When overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType() GetType() GetType() GetType()

Obtém o tipo de tempo de execução da instância atual.Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Cria e retorna uma representação de cadeia de caracteres da exceção atual.Creates and returns a string representation of the current exception.

(Inherited from Exception)

Eventos

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

Aplica-se a

Veja também