将 WebClient 方法转换为 async/await [英] Converting a WebClient method to async / await

查看:29
本文介绍了将 WebClient 方法转换为 async/await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些现有代码可以移植到 Windows 8 WinRT.代码从 URL 获取数据,异步调用传递的委托:

I have some existing code which I am porting to Windows 8 WinRT. The code fetches data from URL, asynchronously invoking a passed delegate:

private void RequestData(string uri, Action<string> action)
{
  var client = new WebClient();
  client.DownloadStringCompleted += (s,e) => action(e.Result);
  client.DownloadStringAsync(new Uri(uri));
}

转换为 WinRT 需要使用 HttpClient 和异步方法.我已经阅读了一些关于 async/await 的教程,但我有点困惑.如何更改上述方法,但保留方法签名以避免更改更多代码?

Converting to WinRT requires the use of HttpClient and asynchronous methods. I've read a few tutorials on async / await, but am a bit baffled. How can I change the method above, but maintain the method signature in order to avoid changing much more of my code?

推荐答案

private async void RequestData(string uri, Action<string> action)
{
    var client = new WebClient();
    string data = await client.DownloadStringTaskAsync(uri);
    action(data);
}

请参阅:http://msdn.microsoft.com/en-us/library/hh194294.aspx

这篇关于将 WebClient 方法转换为 async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆