FileStream.EndRead(IAsyncResult) Método

Definição

Espera que a operação de leitura assíncrona pendente seja concluída. (Considere usar ReadAsync(Byte[], Int32, Int32, CancellationToken) em vez disso.)

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 ao pedido assíncrono pendente para aguardar.

Devoluções

O número de bytes lidos do fluxo, entre 0 e o número de bytes que solicitou. Os fluxos só retornam 0 no final do fluxo, caso contrário, devem bloquear até que pelo menos 1 byte esteja disponível.

Exceções

asyncResult é null.

Este IAsyncResult objeto não foi criado ao invocar BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) esta classe.

O fluxo está encerrado ou ocorreu um erro interno.

Exemplos

Este exemplo de código faz parte de um exemplo maior fornecido ao FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) construtor.

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();
}
let endReadCallback (asyncResult: IAsyncResult) =
    let tempState = asyncResult.AsyncState :?> State
    let readCount = tempState.FStream.EndRead asyncResult

    let mutable i = 0
    let mutable errored = false

    while i < readCount do
        if tempState.ReadArray[i] <> tempState.WriteArray[i] then
            printfn "Error writing data."
            tempState.FStream.Close()
            errored <- true
            i <- readCount

        i <- i + 1

    printfn $"The data was written to {tempState.FStream.Name} and verified."
    tempState.FStream.Close()
    // Signal the main thread that the verification is finished.
    tempState.ManualEvent.Set() |> ignore
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

Observações

No .NET Framework 4 e versões anteriores, é necessário usar métodos como BeginRead e EndRead para implementar operações de ficheiros assíncronas. Estes métodos ainda estão disponíveis no .NET Framework 4.5 para suportar código legado; no entanto, os novos métodos assíncronos, como ReadAsync, WriteAsync, CopyToAsync e FlushAsync, ajudam a implementar operações de ficheiros assíncronas de forma mais fácil.

EndRead deve ser chamado exatamente para cada chamada para BeginRead. Não terminar um processo de leitura antes de iniciar outra leitura pode causar comportamentos indesejáveis, como deadlock.

Este método substitui o EndRead.

EndRead pode ser chamado em cada IAsyncResult a partir de BeginRead. A chamada EndRead indica quantos bytes foram lidos do fluxo. EndRead irá bloquear até que a operação de E/S esteja concluída.

Aplica-se a

Ver também