对于返回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  }

 

 

 

  

你可能感兴趣的:(wait)