对于返回void类型的asyc的异步方法,如何修改,能使用await
2014-01-05 12:03
597 查看
下面是使用WebClinet 获取百度首页的html代码,一般的写法如下:
接下来是如何使用await:
首先添加一个扩展类
接下来使用await
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; }
相关文章推荐
- main之前
- Design stack containing min function
- Conversion to Dalvik format failed: Unable to execute dex: 。。。bin
- USACO Section1.3 Barn Repair
- Container With Most Water
- swing 中paint与paintComponent的区别(jcomponent)
- 253 - Cube painting
- dojo之TabContainer篇
- RAID在企业服务器中的应用(RAID几种级别)
- Climbing Stairs
- AIX上解压缩.tar.Z, .tar.gz, .zip及.tgz
- rails console --sandbox出现的安装错误解决方案
- cf-208B - Solitaire-记录状态DFS
- uva 10617 Again Palindromes(DP)
- CairoSVG - Convert SVG to PNG or PDF - Contents
- retain和release倒底怎么玩?
- cairo graphics.org
- Failed to allocate memory: 8 (andriod模拟器无法启动)
- sleep和wait区别
- ImportError: No module named Image IOError: decoder zip not available