Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a WebClient method to async / await

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?

like image 406
ColinE Avatar asked Nov 05 '12 21:11

ColinE


2 Answers

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

like image 150
Cole Cameron Avatar answered Sep 21 '22 15:09

Cole Cameron


How can I change the method above, but maintain the method signature in order to avoid changing much more of my code?

The best answer is "you don't". If you use async, then use it all the way down.

private async Task<string> RequestData(string uri) {   using (var client = new HttpClient())   {     return await client.GetStringAsync(uri);   } } 
like image 20
Stephen Cleary Avatar answered Sep 24 '22 15:09

Stephen Cleary