FileStream.EndRead(IAsyncResult) FileStream.EndRead(IAsyncResult) FileStream.EndRead(IAsyncResult) FileStream.EndRead(IAsyncResult) Method

Definição

Aguarda a operação de leitura assíncrona pendente ser concluída.Waits for the pending asynchronous read operation to complete. (Considere o uso de ReadAsync(Byte[], Int32, Int32, CancellationToken) em seu lugar.)(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

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

asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

A referência à solicitação assíncrona pendente que deverá ser aguardada.The reference to the pending asynchronous request to wait for.

Retornos

O número de bytes lidos do fluxo, entre 0 e o número de bytes solicitado.The number of bytes read from the stream, between 0 and the number of bytes you requested. Os fluxos retornam somente 0 no final do fluxo, caso contrário, eles devem ser bloqueados até que pelo menos 1 byte esteja disponível.Streams only return 0 at the end of the stream, otherwise, they should block until at least 1 byte is available.

Exceções

O fluxo está fechado ou ocorreu um erro interno.The stream is closed or an internal error has occurred.

Exemplos

Este exemplo de código é parte de um exemplo maior fornecido para o FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) construtor.This code example is part of a larger example provided for the FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) constructor.

   static void EndReadCallback( IAsyncResult^ asyncResult )
   {
      State^ tempState = dynamic_cast<State^>(asyncResult->AsyncState);
      int readCount = tempState->FStream->EndRead( asyncResult );
      int i = 0;
      while ( i < readCount )
      {
         if ( tempState->ReadArray[ i ] != tempState->WriteArray[ i++ ] )
         {
            Console::WriteLine( "Error writing data." );
            tempState->FStream->Close();
            return;
         }
      }

      Console::WriteLine( "The data was written to {0} "
      "and verified.", tempState->FStream->Name );
      tempState->FStream->Close();
      
      // Signal the main thread that the verification is finished.
      tempState->ManualEvent->Set();
   }


public:

static void EndReadCallback(IAsyncResult asyncResult)
{
    State tempState = (State)asyncResult.AsyncState;
    int readCount = tempState.FStream.EndRead(asyncResult);

    int i = 0;
    while(i < readCount)
    {
        if(tempState.ReadArray[i] != tempState.WriteArray[i++])
        {
            Console.WriteLine("Error writing data.");
            tempState.FStream.Close();
            return;
        }
    }
    Console.WriteLine("The data was written to {0} and verified.",
        tempState.FStream.Name);
    tempState.FStream.Close();

    // Signal the main thread that the verification is finished.
    tempState.ManualEvent.Set();
}
Private Shared Sub EndReadCallback(asyncResult As IAsyncResult)
     Dim tempState As State = _
         DirectCast(asyncResult.AsyncState, State)
     Dim readCount As Integer = _
         tempState.FStream.EndRead(asyncResult)

     Dim i As Integer = 0
     While(i < readCount)
         If(tempState.ReadArray(i) <> tempState.WriteArray(i))
             Console.WriteLine("Error writing data.")
             tempState.FStream.Close()
             Return
         End If
         i += 1
     End While

     Console.WriteLine("The data was written to {0} and " & _
         "verified.", tempState.FStream.Name)
     tempState.FStream.Close()

     ' Signal the main thread that the verification is finished.
     tempState.ManualEvent.Set()
 End Sub

Comentários

No .NET Framework 4 e versões anteriores, você precisa usar métodos como BeginRead e EndRead para implementar operações de arquivo assíncrono.In the .NET Framework 4 and earlier versions, you have to use methods such as BeginRead and EndRead to implement asynchronous file operations. Esses métodos ainda estão disponíveis na .NET Framework 4.5.NET Framework 4.5 para dar suporte ao código herdado; no entanto, os novos métodos assíncronos, como ReadAsync, WriteAsync, CopyToAsync, e FlushAsync, ajudam a implementar operações de arquivo assíncronas com mais facilidade.These methods are still available in the .NET Framework 4.5.NET Framework 4.5 to support legacy code; however, the new async methods, such as ReadAsync, WriteAsync, CopyToAsync, and FlushAsync, help you implement asynchronous file operations more easily.

EndRead deve ser chamado exatamente para que todas as chamadas para BeginRead.EndRead must be called exactly for every call to BeginRead. Falha ao encerrar um processo de leitura antes de iniciar outra leitura pode causar um comportamento indesejável, como o deadlock.Failing to end a read process before beginning another read can cause undesirable behavior such as deadlock.

Este método substitui EndRead.This method overrides EndRead.

EndRead pode ser chamado em cada IAsyncResult de BeginRead.EndRead can be called on every IAsyncResult from BeginRead. Chamar EndRead informa quantos bytes foram lidos do fluxo.Calling EndRead tells you how many bytes were read from the stream. EndRead será bloqueada até que a operação de e/s seja concluída.EndRead will block until the I/O operation has completed.

Aplica-se a

Veja também