我目前正在使用 Xamarin 免费试用版开发概念验证应用程序,并且遇到了一个相当有趣的小问题......这是我在可移植类库中使用的代码:
using System;
using System.Net;
using Newtonsoft.Json;
namespace poc
{
public class CurrentWeatherInformation
{
public string WeatherText { get; set; }
public CurrentWeatherInformation (string cityName)
{
// api.openweathermap.org/data/2.5/weather?q=Leeds
var request = (HttpWebRequest)WebRequest.Create(string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}", cityName));
request.ContentType = "application/json";
request.Method = "GET";
object state = request;
var ar = request.BeginGetResponse (WeatherCallbackMethod, state);
var waitHandle = ar.AsyncWaitHandle as System.Threading.ManualResetEvent;
waitHandle.WaitOne();
}
public void WeatherCallbackMethod(IAsyncResult ar)
{
object state = ar.AsyncState;
var request = state as HttpWebRequest;
var response = request.EndGetResponse(ar);
var data = new System.IO.StreamReader (response.GetResponseStream ()).ReadToEnd ();
this.WeatherText = data;
}
}
}
本质上,我只是想针对 Web 服务调用并获得响应,但我注意到 Xamarin 无法使用旧方法执行此操作,而GetResponse()
必须使用旧模式。嘘。BeginGetResponse()
EndGetResponse()
IAsyncResult
无论如何,我的问题是我等待之后waitHandle
的代码在回调中的代码之前执行,我不明白为什么。这正是我们等待处理的原因!
谁能发现我确信会被一个傻瓜证明是一个简单的错误?