问题
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?
回答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
回答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);
}
}
回答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;
回答4:
var client = new WebClient();
string page = await client.DownloadStringTaskAsync("url");
or
var client = new HttpClient();
string page = await client.GetStringAsync("url");
回答5:
await
the result of the HttpClient.GetStringAsync Method:
var client = new HttpClient();
action(await client.GetStringAsync(uri));
回答6:
And this piece of code is for UploadValuesAsync:
public class WebClientAdvanced : WebClient
{
public async Task<byte[]> UploadValuesAsync(string address, string method, IDictionary<string, string> data)
{
var nvc = new NameValueCollection();
foreach (var x in data) nvc.Add(x.Key, x.Value.ToStr());
var tcs = new TaskCompletionSource<byte[]>();
UploadValuesCompleted += (s, e) =>
{
if (e.Cancelled) tcs.SetCanceled();
else if (e.Error != null) tcs.SetException(e.Error);
else tcs.SetResult(e.Result);
};
UploadValuesAsync(new Uri(address), method, nvc);
var result = await tcs.Task;
return result;
}
}
来源:https://stackoverflow.com/questions/13240915/converting-a-webclient-method-to-async-await