Converting a WebClient method to async / await
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
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);
}
}
Following this example, you first create the async task wtih, then get its result using await
:
Task<string> downloadStringTask = client.DownloadStringTaskAsync(new Uri(uri));
string result = await downloadStringTask;