FileStream.EndRead(IAsyncResult) Método

Definição

Aguarda a operação de leitura assíncrona pendente ser concluída. (Considere o uso de ReadAsync(Byte[], Int32, Int32, CancellationToken) em seu lugar.)

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

A referência à solicitação assíncrona pendente que deverá ser aguardada.

Retornos

Int32

O número de bytes lidos do fluxo, entre 0 e o número de bytes solicitado. 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.

Exceções

asyncResult é null.

O fluxo está fechado ou ocorreu um erro interno.

Exemplos

Este exemplo de código é parte de um exemplo maior fornecido para o FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) Construtor.

   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. esses métodos ainda estão disponíveis no .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 você a implementar operações de arquivo assíncrono com mais facilidade.

EndRead deve ser chamado exatamente para cada chamada para BeginRead . A falha ao encerrar um processo de leitura antes de iniciar outra leitura pode causar um comportamento indesejável, como o deadlock.

Este método substitui EndRead.

EndRead pode ser chamado em cada IAsyncResult de BeginRead . EndReadA chamada informa quantos bytes foram lidos a partir do fluxo. EndRead será bloqueado até que a operação de e/s seja concluída.

Aplica-se a

Confira também