7

如何在 Windows Phone 8 中将await与 HttpWebRequest 一起使用?

有没有办法让 IAsyncResult 的东西与 await 一起工作?

private async Task<int> GetCurrentTemperature()
{
  GeoCoordinate location = GetLocation();

  string url = "http://free.worldweatheronline.com/feed/weather.ashx?q=";
  url += location.Latitude.ToString();
  url += ",";
  url += location.Longitude.ToString();
  url += "&format=json&num_of_days=1&key=MYKEY";

  HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
  webRequest.Method = "POST";
  webRequest.BeginGetResponse(new AsyncCallback(OnGotWebRequest), webRequest);
}

private void OnGotWebRequest(IAsyncResult asyncResult)
{
  HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
  var httpResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  {
    string responseText = streamReader.ReadToEnd();
  }
}

谢谢!

4

2 回答 2

16

用于从/方法TaskFactory.FromAsync创建一个。然后你可以完全摆脱你的,并为响应做同样的事情。Task<Stream>BeginGetRequestStreamEndGetRequestStreamOnGotWebRequest

请注意,当前您正在调用完成EndGetResponseBeginGetRequestStream调用,这是不合适的开始 - 您必须调用该EndFoo方法以匹配BeginFoo您最初调用的方法。你的意思是打电话BeginGetResponse吗?

于 2012-12-05T22:38:48.407 回答
4

如果您安装Microsoft.Bcl.Async包,您将获得一些async现成的扩展方法,包括用于HttpWebRequest.

于 2012-12-06T01:50:21.907 回答