Is there any way to await an IAsyncResult in Windo

2019-02-17 04:53发布

问题:

How can I use await with HttpWebRequest in Windows Phone 8 ?

Is there a way to make the IAsyncResult stuff work with 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();
  }
}

Thanks!

回答1:

Use TaskFactory.FromAsync to create a Task<Stream> from the BeginGetRequestStream/EndGetRequestStream methods. Then you can get rid of your OnGotWebRequest completely, and do the same thing for the response.

Note that currently you're calling EndGetResponse when a BeginGetRequestStream call completes, which is inappropriate to start with - you've got to call the EndFoo method to match the BeginFoo you originally called. Did you mean to call BeginGetResponse?



回答2:

If you install the Microsoft.Bcl.Async package, you get a few async-ready extension methods, including ones for HttpWebRequest.