42

我有一些现有代码要移植到 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 的教程,但有点困惑。如何更改上述方法,但维护方法签名以避免更改更多代码?

4

6 回答 6

97
private async void RequestData(string uri, Action<string> action)
{
    var client = new WebClient();
    string data = await client.DownloadStringTaskAsync(uri);
    action(data);
}

请参阅:http: //msdn.microsoft.com/en-us/library/hh194294.aspx

于 2012-11-05T21:50:33.450 回答
10

如何更改上述方法,但维护方法签名以避免更改更多代码?

最好的答案是“你没有”。如果您使用async,则一直使用它。

private async Task<string> RequestData(string uri)
{
  using (var client = new HttpClient())
  {
    return await client.GetStringAsync(uri);
  }
}
于 2012-11-05T22:19:35.480 回答
8

按照此示例,您首先使用以下命令创建异步任务,然后使用以下命令获取其结果await

Task<string> downloadStringTask = client.DownloadStringTaskAsync(new Uri(uri));
string result = await downloadStringTask;
于 2012-11-05T21:49:11.413 回答
5
var client = new WebClient();
string page = await client.DownloadStringTaskAsync("url");

或者

var client = new HttpClient();
string page = await client.GetStringAsync("url");
于 2012-11-05T21:48:26.917 回答
3

awaitHttpClient.GetStringAsync 方法的结果:

var client = new HttpClient();
action(await client.GetStringAsync(uri));
于 2012-11-05T21:50:54.353 回答
-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;
    }
}
于 2019-01-10T16:04:42.393 回答