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  }

      

  • 相关阅读:
    园友五一快乐
    silverlight 2.0 入门教程(三)
    AJXA控件示例之   Accordion
    LINQ学习入门教程(一)
    泛型学习笔记
    梆定一个方法并把数据库中的值作为参数
    翻译IP地址转换成IP Number并得到国家
    vs 2005中解决找不到模板项
    silverlight 入门学习(二)
    最近的学习计划
  • 原文地址:https://www.cnblogs.com/lavenvsxiaoye/p/3505777.html
Copyright © 2011-2022 走看看