转换一个WebClient的方法来异步/的await [英] Converting a WebClient method to async / await
问题描述
我有一些现有的code这我移植到Windows 8的WinRT的。在code从URL获取数据,异步调用通过委托:
私人无效的RequestData(字符串URI,动作<串GT;动作)
{
VAR的客户=新的WebClient();
client.DownloadStringCompleted + =(S,E)=>动作(e.Result);
client.DownloadStringAsync(新的URI(URI));
}
转换为WinRT中需要使用的HttpClient
和异步方法。我已经在异步/的await读了一些教程,但我有点困惑。如何更改上面的方法,但保持方法签名,以避免改变更我的code的?
专用异步无效的RequestData(字符串URI,动作<串GT;动作)
{
VAR的客户=新的WebClient();
字符串数据=等待client.DownloadStringTaskAsync(URI);
动作(数据);
}
请参阅:<一href=\"http://msdn.microsoft.com/en-us/library/hh194294.aspx\">http://msdn.microsoft.com/en-us/library/hh194294.aspx
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));
}
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);
}
See: http://msdn.microsoft.com/en-us/library/hh194294.aspx
这篇关于转换一个WebClient的方法来异步/的await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!