WebClient.OpenReadCompleted 事件

定义

当异步操作打开包含资源的流完成时发生。

public:
 event System::Net::OpenReadCompletedEventHandler ^ OpenReadCompleted;
public event System.Net.OpenReadCompletedEventHandler? OpenReadCompleted;
public event System.Net.OpenReadCompletedEventHandler OpenReadCompleted;
member this.OpenReadCompleted : System.Net.OpenReadCompletedEventHandler 
Public Custom Event OpenReadCompleted As OpenReadCompletedEventHandler 
Public Event OpenReadCompleted As OpenReadCompletedEventHandler 

事件类型

示例

下面的代码示例演示如何为此事件设置事件处理程序。

void OpenResourceForReading2( String^ address )
{
   WebClient^ client = gcnew WebClient;
   Uri ^uri = gcnew Uri(address);

   client->OpenReadCompleted += gcnew OpenReadCompletedEventHandler( OpenReadCallback2 );
   client->OpenReadAsync( uri );
}
public static void OpenResourceForReading2(string address)
{
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    client.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCallback2);
    client.OpenReadAsync(uri);
}
Public Shared Sub OpenResourceForReading2(ByVal address As String)

    Dim client As WebClient = New WebClient()
    AddHandler client.OpenReadCompleted, AddressOf OpenReadCallback2
                Dim uri as Uri = New Uri(address)
    client.OpenReadAsync(uri)
End Sub

下面的代码示例演示此事件的处理程序的实现。

void OpenReadCallback2( Object^ /*sender*/, OpenReadCompletedEventArgs^ e )
{
   Stream^ reply = nullptr;
   StreamReader^ s = nullptr;
   try
   {
      reply = dynamic_cast<Stream^>(e->Result);
      s = gcnew StreamReader( reply );
      Console::WriteLine( s->ReadToEnd() );
   }
   finally
   {
      if ( s != nullptr )
      {
         s->Close();
      }
      if ( reply != nullptr )
      {
         reply->Close();
      }
   }

}
private static void OpenReadCallback2(Object sender, OpenReadCompletedEventArgs e)
{
    Stream reply = null;
    StreamReader s = null;

    try
    {
        reply = (Stream)e.Result;
        s = new StreamReader(reply);
        Console.WriteLine(s.ReadToEnd());
    }
    finally
    {
        if (s != null)
        {
            s.Close();
        }

        if (reply != null)
        {
            reply.Close();
        }
    }
}
Private Shared Sub OpenReadCallback2(ByVal sender As Object, ByVal e As OpenReadCompletedEventArgs)

    Dim reply As Stream = Nothing
    Dim s As StreamReader = Nothing

    Try

        reply = CType(e.Result, Stream)
        s = New StreamReader(reply)
        Console.WriteLine(s.ReadToEnd())
    Finally

        If Not s Is Nothing Then

            s.Close()
        End If

        If Not reply Is Nothing Then

            reply.Close()
        End If
    End Try
End Sub

注解

谨慎

WebRequestHttpWebRequestServicePointWebClient 已过时,不应将其用于新开发。 请改用 HttpClient

每次异步操作打开包含资源完成的流时都会引发此事件。 这些操作通过调用 OpenReadAsync 方法启动。

OpenReadCompletedEventHandler 是此事件的委托。 OpenReadCompletedEventArgs 类为事件处理程序提供事件数据。

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于