如何在Windows Phone 8中使用等待與HttpWebRequest?有什麼辦法可以等待Windows Phone 8中的IAsyncResult?
有沒有辦法使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();
}
}
謝謝!
你是對的開始/結束。謝謝! – swinefeaster
你能舉一個例子來說明如何創建和使用任務? –
我在[這個問題上找到了一個完美的工作示例](http://stackoverflow.com/a/14098942/831825)。 –