有没有办法在Windows Phone 8中等待IAsyncResult?

时间:2012-12-05 22:36:01

标签: c# asynchronous windows-phone windows-phone-8

如何在Windows Phone 8中使用等待与HttpWebRequest一起使用?

有没有办法让IAsyncResult的东西能够等待?

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();
  }
}

谢谢!

2 个答案:

答案 0 :(得分:16)

使用TaskFactory.FromAsyncTask<Stream> / BeginGetRequestStream方法创建EndGetRequestStream。然后你可以完全摆脱你的OnGotWebRequest,并为响应做同样的事情。

请注意,当EndGetResponse调用完成时,您正在调用BeginGetRequestStream,这不适合开始使用 - 您必须调用EndFoo方法来匹配BeginFoo 1}}你最初打过电话。您的意思是打电话给BeginGetResponse吗?

答案 1 :(得分:4)

如果您安装了Microsoft.Bcl.Async软件包,则会获得一些async - 就绪扩展方法,包括HttpWebRequest的方法。