zoukankan      html  css  js  c++  java
  • 对于返回void类型的asyc的异步方法,如何修改,能使用await

    下面是使用WebClinet 获取百度首页的html代码,一般的写法如下:

     1 private void Button_Click(object sender, RoutedEventArgs e)
     2 {
     3     WebClient client = new System.Net.WebClient();
     4     client.OpenReadAsync(new Uri("http://www.baidu.com/"));
     5     client.OpenReadCompleted += c_OpenReadCompleted;
     6 }
     7 void c_OpenReadCompleted(object sender, System.Net.OpenReadCompletedEventArgs e)
     8 {
     9     StreamReader reader = new StreamReader(e.Result);
    10     string content = reader.ReadToEnd();
    11     MessageBox.Show(content);
    12 } 

    接下来是如何使用await:

    首先添加一个扩展类

      

     1 public static class WebClientExtend
     2 {
     3     public static Task<Stream> OpenReadAsync(this WebClient webClient, string url)
     4     {
     5         TaskCompletionSource<Stream> source = new TaskCompletionSource<Stream>();
     6         webClient.OpenReadCompleted += (sender, e) =>
     7         {
     8             if (e.Error != null)
     9             {
    10                 source.TrySetException(e.Error);
    11             }
    12             else
    13             {
    14                 source.SetResult(e.Result);
    15             }
    16         };
    17         webClient.OpenReadAsync(new Uri(url, UriKind.RelativeOrAbsolute));
    18         return source.Task;
    19     }
    20 
    21 }

    接下来使用await

    1  private async void Button_Click(object sender, RoutedEventArgs e)
    2  {
    3      WebClient client = new System.Net.WebClient();
    4      Stream stream = await client.OpenReadAsync("http://www.baidu.com/");
    5      StreamReader reader = new StreamReader(stream);
    6      string content = reader.ReadToEnd();
    7      MessageBox.Show(content);
    8      //client.OpenReadCompleted += c_OpenReadCompleted; 
    9  }

      

  • 相关阅读:
    搭建 structs2 环境
    数据库基础
    好书推荐整理
    Java 完美判断中文字符
    中文在unicode中的编码范围
    [转载]爬虫的自我解剖(抓取网页HtmlUnit)
    web应用配置
    简单的Java Web服务器
    dos基本命令
    Unrecognized Windows Sockets error: 0: JVM_Bind
  • 原文地址:https://www.cnblogs.com/lavenvsxiaoye/p/3505777.html
Copyright © 2011-2022 走看看