title: Wait Handles and Xamarin Forms
body: <p>I am currently working on a proof of concept application using the Xamarin free trial, and I have hit a rather interesting little problem... Here is the code I am using within a Portable Class Library:</p>
  
  <pre><code>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;
          }
  
      }
  }
  </code></pre>
  
  <p>Essentially, I just want to call against a webservice and get a response, but I note with Xamarin that I am unable to do this using the good old <code>GetResponse()</code> method, and have to use <code>BeginGetResponse()</code> and <code>EndGetResponse()</code> instead, with the old <code>IAsyncResult</code> pattern. Shizzle.</p>
  
  <p>Anyway, my problem is that the code following my waiting on the <code>waitHandle</code> is executing BEFORE the code in the callback, and I don't see why. This is precisely what we have the wait handle for! </p>
  
  <p>Can anyone spot what I am sure will prove to be a simple mistake by a simpleton?</p>