FtpWebRequest.BeginGetResponse(AsyncCallback, Object) Método

Definição

Começa a enviar uma solicitação e receber uma resposta de um servidor FTP de maneira assíncrona.Begins sending a request and receiving a response from an FTP server asynchronously.

public:
 override IAsyncResult ^ BeginGetResponse(AsyncCallback ^ callback, System::Object ^ state);
public override IAsyncResult BeginGetResponse (AsyncCallback? callback, object? state);
public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state);
override this.BeginGetResponse : AsyncCallback * obj -> IAsyncResult
Public Overrides Function BeginGetResponse (callback As AsyncCallback, state As Object) As IAsyncResult

Parâmetros

callback
AsyncCallback

Um delegado AsyncCallback que faz referência ao método a ser invocado quando a operação é concluída.An AsyncCallback delegate that references the method to invoke when the operation is complete.

state
Object

Um objeto definido pelo usuário que contém informações sobre a operação.A user-defined object that contains information about the operation. Esse objeto é passado para o representante callback quando a operação é concluída.This object is passed to the callback delegate when the operation completes.

Retornos

IAsyncResult

Um instância de IAsyncResult que indica o status da operação.An IAsyncResult instance that indicates the status of the operation.

Exceções

GetResponse() ou BeginGetResponse(AsyncCallback, Object) já foi chamado para essa instância.GetResponse() or BeginGetResponse(AsyncCallback, Object) has already been called for this instance.

Exemplos

O exemplo de código a seguir demonstra como encerrar uma operação assíncrona para obter o fluxo de uma solicitação e, em seguida, iniciar uma solicitação para obter a resposta.The following code example demonstrates ending an asynchronous operation to get a request's stream, and then starting a request to get the response. Este exemplo de código é parte de um exemplo maior fornecido para a FtpWebRequest visão geral da classe.This code example is part of a larger example provided for the FtpWebRequest class overview.

private:
   static void EndGetStreamCallback( IAsyncResult^ ar )
   {
      FtpState^ state = dynamic_cast<FtpState^>(ar->AsyncState);
      Stream^ requestStream = nullptr;

      // End the asynchronous call to get the request stream.
      try
      {
         requestStream = state->Request->EndGetRequestStream( ar );

         // Copy the file contents to the request stream.
         const int bufferLength = 2048;
         array<Byte>^buffer = gcnew array<Byte>(bufferLength);
         int count = 0;
         int readBytes = 0;
         FileStream^ stream = File::OpenRead( state->FileName );
         do
         {
            readBytes = stream->Read( buffer, 0, bufferLength );
            requestStream->Write( buffer, 0, bufferLength );
            count += readBytes;
         }
         while ( readBytes != 0 );
         Console::WriteLine( "Writing {0} bytes to the stream.", count );

         // IMPORTANT: Close the request stream before sending the request.
         requestStream->Close();

         // Asynchronously get the response to the upload request.
         state->Request->BeginGetResponse( gcnew AsyncCallback( EndGetResponseCallback ), state );
      }
      // Return exceptions to the main application thread.
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "Could not get the request stream." );
         state->OperationException = e;
         state->OperationComplete->Set();
         return;
      }
   }
private static void EndGetStreamCallback(IAsyncResult ar)
{
    FtpState state = (FtpState) ar.AsyncState;

    Stream requestStream = null;
    // End the asynchronous call to get the request stream.
    try
    {
        requestStream = state.Request.EndGetRequestStream(ar);
        // Copy the file contents to the request stream.
        const int bufferLength = 2048;
        byte[] buffer = new byte[bufferLength];
        int count = 0;
        int readBytes = 0;
        FileStream stream = File.OpenRead(state.FileName);
        do
        {
            readBytes = stream.Read(buffer, 0, bufferLength);
            requestStream.Write(buffer, 0, readBytes);
            count += readBytes;
        }
        while (readBytes != 0);
        Console.WriteLine ("Writing {0} bytes to the stream.", count);
        // IMPORTANT: Close the request stream before sending the request.
        requestStream.Close();
        // Asynchronously get the response to the upload request.
        state.Request.BeginGetResponse(
            new AsyncCallback (EndGetResponseCallback),
            state
        );
    }
    // Return exceptions to the main application thread.
    catch (Exception e)
    {
        Console.WriteLine("Could not get the request stream.");
        state.OperationException = e;
        state.OperationComplete.Set();
        return;
    }
}

Comentários

Você deve concluir a operação assíncrona chamando o EndGetResponse método.You must complete the asynchronous operation by calling the EndGetResponse method. Normalmente, EndGetResponse é chamado pelo método referenciado por callback .Typically, EndGetResponse is called by the method referenced by callback. Para determinar o estado da operação, verifique as propriedades no IAsyncResult objeto retornado pelo BeginGetResponse método.To determine the state of the operation, check the properties in the IAsyncResult object returned by the BeginGetResponse method.

Se a Proxy propriedade for definida, diretamente ou em um arquivo de configuração, as comunicações com o servidor FTP serão feitas por meio do proxy especificado.If the Proxy property is set, either directly or in a configuration file, communications with the FTP server are made through the specified proxy.

BeginGetResponse Não é bloqueado enquanto aguarda a resposta do servidor.BeginGetResponse does not block while waiting for the response from the server. Para bloquear, chame o GetResponse método no lugar de BeginGetResponse .To block, call the GetResponse method in place of BeginGetResponse.

Para obter mais informações sobre como usar o modelo de programação assíncrona, consulte chamando métodos síncronos de formaassíncrona.For more information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously.

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede na .NET Framework.For more information, see Network Tracing in the .NET Framework.

Observação

Se um WebException for gerado, use as Response Status Propriedades e da exceção para determinar a resposta do servidor.If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

Notas aos Chamadores

Esse método gera o tráfego de rede.This method generates network traffic.

Aplica-se a

Confira também