【问题标题】:Is there any way to await an IAsyncResult in Windows Phone 8?有什么方法可以在 Windows Phone 8 中等待 IAsyncResult?
【发布时间】:2012-12-05 22:36:00
【问题描述】:

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

    使用TaskFactory.FromAsyncBeginGetRequestStream/EndGetRequestStream 方法创建一个Task&lt;Stream&gt;。然后你就可以彻底摆脱你的OnGotWebRequest,对回复做同样的事情。

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

    【讨论】:

    • 能否给我们举个例子来说明如何创建和使用Task
    • 我在this question on SO找到了一个完美的工作示例。
    【解决方案2】:

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

    【讨论】:

    • 这些天我偶然发现了this blog post,它解释了如何在 WP8 中使用 Microsoft.Bcl.Async 包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2015-04-16
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多