Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to await an IAsyncResult in Windows Phone 8?

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!

like image 981
swinefeaster Avatar asked Dec 05 '12 22:12

swinefeaster


1 Answers

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?

like image 94
Jon Skeet Avatar answered Sep 27 '22 19:09

Jon Skeet