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!
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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With