您的位置:首页 > 大数据 > 人工智能

对于返回void类型的asyc的异步方法,如何修改,能使用await

2014-01-05 12:03 597 查看
下面是使用WebClinet 获取百度首页的html代码,一般的写法如下:

private void Button_Click(object sender, RoutedEventArgs e)
{
WebClient client = new System.Net.WebClient();
client.OpenReadAsync(new Uri("http://www.baidu.com/"));
client.OpenReadCompleted += c_OpenReadCompleted;
}
void c_OpenReadCompleted(object sender, System.Net.OpenReadCompletedEventArgs e)
{
StreamReader reader = new StreamReader(e.Result);
string content = reader.ReadToEnd();
MessageBox.Show(content);
}


接下来是如何使用await:

首先添加一个扩展类

public static class WebClientExtend
{
public static Task<Stream> OpenReadAsync(this WebClient webClient, string url)
{
TaskCompletionSource<Stream> source = new TaskCompletionSource<Stream>();
webClient.OpenReadCompleted += (sender, e) =>
{
if (e.Error != null)
{
source.TrySetException(e.Error);
}
else
{
source.SetResult(e.Result);
}
};
webClient.OpenReadAsync(new Uri(url, UriKind.RelativeOrAbsolute));
return source.Task;
}

}


接下来使用await

private async void Button_Click(object sender, RoutedEventArgs e)
{
WebClient client = new System.Net.WebClient();
Stream stream = await client.OpenReadAsync("http://www.baidu.com/");
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
MessageBox.Show(content);
//client.OpenReadCompleted += c_OpenReadCompleted;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: