NegotiateStream.EndRead(IAsyncResult) Método

Definição

Encerra uma operação de leitura assíncrona que foi iniciada com uma chamada para BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).Ends an asynchronous read operation that was started with a call to BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

public:
 override int EndRead(IAsyncResult ^ asyncResult);
public override int EndRead (IAsyncResult asyncResult);
override this.EndRead : IAsyncResult -> int
Public Overrides Function EndRead (asyncResult As IAsyncResult) As Integer

Parâmetros

Retornos

Int32

Um valor Int32 que especifica o número de bytes lidos do fluxo subjacente.A Int32 value that specifies the number of bytes read from the underlying stream.

Exceções

asyncResult é null.asyncResult is null.

O asyncResult não foi criado por uma chamada para BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).The asyncResult was not created by a call to BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

Não há nenhuma operação de leitura pendente a ser concluída.There is no pending read operation to complete.

- ou --or-

A autenticação não ocorreu.Authentication has not occurred.

Falha na operação de leitura.The read operation failed.

Exemplos

O exemplo de código a seguir demonstra como encerrar uma operação de leitura assíncrona.The following code example demonstrates ending an asynchronous read operation. Para obter um exemplo que demonstra como iniciar a operação, consulte BeginRead .For an example that demonstrates starting the operation, see BeginRead.

static void EndReadCallback( IAsyncResult^ ar )
{
   
   // Get the saved data.
   ClientState^ cState = dynamic_cast<ClientState^>(ar->AsyncState);
   TcpClient^ clientRequest = cState->Client;
   NegotiateStream^ authStream = dynamic_cast<NegotiateStream^>(cState->AuthStream);
   
   // Get the buffer that stores the message sent by the client.
   int bytes = -1;
   
   // Read the client message.
   try
   {
      bytes = authStream->EndRead( ar );
      cState->Message->Append( Encoding::UTF8->GetChars( cState->Buffer, 0, bytes ) );
      if ( bytes != 0 )
      {
         authStream->BeginRead( cState->Buffer, 0, cState->Buffer->Length, gcnew AsyncCallback( EndReadCallback ), cState );
         return;
      }
   }
   catch ( Exception^ e ) 
   {
      
      // A real application should do something
      // useful here, such as logging the failure.
      Console::WriteLine( L"Client message exception:" );
      Console::WriteLine( e );
      cState->Waiter->Set();
      return;
   }

   IIdentity^ id = authStream->RemoteIdentity;
   Console::WriteLine( L"{0} says {1}", id->Name, cState->Message );
   cState->Waiter->Set();
}

private static void EndReadCallback(ClientState cState, int bytes)
{
    NegotiateStream authStream = (NegotiateStream)cState.AuthenticatedStream;
    // Read the client message.
    try
    {
        cState.Message.Append(Encoding.UTF8.GetChars(cState.Buffer, 0, bytes));
        if (bytes != 0)
        {
            Task<int> readTask = authStream.ReadAsync(cState.Buffer, 0, cState.Buffer.Length);
            readTask
                .ContinueWith(task => { EndReadCallback(cState, task.Result); })
                .Wait();

            return;
        }
    }
    catch (Exception e)
    {
        // A real application should do something
        // useful here, such as logging the failure.
        Console.WriteLine("Client message exception:");
        Console.WriteLine(e);
        return;
    }
    IIdentity id = authStream.RemoteIdentity;
    Console.WriteLine("{0} says {1}", id.Name, cState.Message.ToString());
}

Comentários

Se a operação não tiver sido concluída, esse método será bloqueado até que ele seja.If the operation has not completed, this method blocks until it does.

Para executar essa operação de forma síncrona, use o Read método.To perform this operation synchronously, use the Read method.

Você não pode chamar esse método até que você tenha autenticado com êxito.You cannot call this method until you have successfully authenticated. Para autenticar, chame um dos AuthenticateAsClient AuthenticateAsClientAsync métodos,, BeginAuthenticateAsClient ,, AuthenticateAsServer AuthenticateAsServerAsync ou BeginAuthenticateAsServer .To authenticate, call one of the AuthenticateAsClient, AuthenticateAsClientAsync, BeginAuthenticateAsClient, AuthenticateAsServer, AuthenticateAsServerAsync, or BeginAuthenticateAsServer methods.

Aplica-se a