3

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:

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;
        }

    }
}

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 GetResponse() method, and have to use BeginGetResponse() and EndGetResponse() instead, with the old IAsyncResult pattern. Shizzle.

Anyway, my problem is that the code following my waiting on the waitHandle is executing BEFORE the code in the callback, and I don't see why. This is precisely what we have the wait handle for!

Can anyone spot what I am sure will prove to be a simple mistake by a simpleton?

Martin Milan
  • 6,346
  • 2
  • 32
  • 44

1 Answers1

2

On Windows Phone you are forced to use the async API. When you try to wait for a result of an async method synchronously on main thread you can end up in an infinite loop. Use async and await when you do expensive things. It's the common pattern for doing asynchronous work.

Take a look at some tutorials:

https://visualstudiomagazine.com/articles/2013/10/01/asynchronous-operations-with-xamarin.aspx

http://developer.xamarin.com/recipes/android/web_services/consuming_services/call_a_rest_web_service/

How to implement Android callbacks in C# using async/await with Xamarin or Dot42?

https://github.com/conceptdev/xamarin-forms-samples/blob/master/HttpClient/HttpClientDemo/GeoNamesWebService.cs

Community
  • 1
  • 1
Wosi
  • 41,986
  • 17
  • 75
  • 82
  • The problem is that (and I've amended my question accordingly) the code I have shown you is in a portable class library, which means that GetResponseAsync etc isn't available. Literally the only option I have is BeginGetResponse and EndGetResponse... – Martin Milan Aug 27 '15 at 11:03
  • 1
    No, you have more options. You can use `System.Net.Http.HttpClient`with `async`/`await`. That's the common way in Xamarin to comsume webservices as shown in the tutorials. – Wosi Aug 27 '15 at 11:09
  • Looks like we can't use System.Net.Http in Xamarin because it's Nuget implementation isn't far enough along (< 3). Tried switching to Visual Studio and now the project doesn't compile. I am starting to get annoyed with this lol... – Martin Milan Aug 27 '15 at 13:26
  • What do you mean with `System.Net.Http` "isn't far enough along"? It's stable and many people use it in their productive apps. – Wosi Aug 27 '15 at 13:28
  • When I try to get the nuget package I am getting a warning that Xamarin's nuget client, being 2.8.3 I think, is not high enough to bring down the package. It claims to need 3 +. Despite that though, it seems that ir has brought down the package... – Martin Milan Aug 27 '15 at 15:30
  • 1
    I'm sorry. Use `Microsoft.Net.Http` instead. The difference is explained here: http://stackoverflow.com/questions/31053243/system-net-http-vs-microsoft-net-http – Wosi Aug 27 '15 at 15:43