Converting a WebClient method to async / await
Solution 1:
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
Solution 2:
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);
}
}
Solution 3:
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;
Solution 4:
var client = new WebClient();
string page = await client.DownloadStringTaskAsync("url");
or
var client = new HttpClient();
string page = await client.GetStringAsync("url");
Solution 5:
await
the result of the HttpClient.GetStringAsync Method:
var client = new HttpClient();
action(await client.GetStringAsync(uri));