我有一些现有的代码,我移植到Windows 8 WinRT。代码从URL获取数据,异步调用传递的委托:
private void RequestData(string uri, Action<string> action)
{
var client = new WebClient();
client.DownloadStringCompleted += (s,e) => action(e.Result);
client.DownloadStringAsync(new Uri(uri));
}
转换为WinRT需要使用HttpClient
和异步方法。我已经阅读了一些关于async / await的教程,但有点困惑。如何更改上述方法,但保留方法签名以避免更改我的代码?
答案 0 :(得分:79)
private async void RequestData(string uri, Action<string> action)
{
var client = new WebClient();
string data = await client.DownloadStringTaskAsync(uri);
action(data);
}
答案 1 :(得分:9)
如何更改上述方法,但保留方法签名以避免更改我的代码?
最好的答案是“你没有”。如果您使用async
,请将其一直使用。
private async Task<string> RequestData(string uri)
{
using (var client = new HttpClient())
{
return await client.GetStringAsync(uri);
}
}
答案 2 :(得分:6)
关注this example,首先使用await
创建异步任务,然后使用Task<string> downloadStringTask = client.DownloadStringTaskAsync(new Uri(uri));
string result = await downloadStringTask;
获取结果:
{{1}}
答案 3 :(得分:4)
var client = new WebClient();
string page = await client.DownloadStringTaskAsync("url");
或
var client = new HttpClient();
string page = await client.GetStringAsync("url");
答案 4 :(得分:3)
await
HttpClient.GetStringAsync Method:
var client = new HttpClient();
action(await client.GetStringAsync(uri));
答案 5 :(得分:-1)
这段代码是针对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;
}
}