Search code examples
c#jsonxamarinxamarin.androidportable-class-library

Program hangs when calling REST API from Xamarin PCL


I have the following code in my Xamarin PCL

    public Product Product(int id)
    {

        var product = Get<Product>(endpoint + "?id=" + id).Result;
        return product;
    }

    static async Task<T> Get<T>(string endpoint)
    {
        using (var client = new HttpClient())
        {
            var response = await client.GetAsync(endpoint);
            string content = await response.Content.ReadAsStringAsync();
            return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
        }
    }

My program just hangs at this line

var response = await client.GetAsync(endpoint);

No exception thrown.

I execute the same code in a console app, and it works fine.

The only difference I could see is that in my console app, I'm referencing Newtonsoft.Json.dll in the lib\net45 folder. In my Xamarin PCL project, I'm referencing Newtonsoft.Json.dll in the lib\portable-net40+sl5+wp80+win8+wpa81 folder. I tried referencing the dll in the lib\portable-net45+wp80+win8+wpa81+dnxcore50 folder, same result.

I'm using Json 8.0.3


Solution

  • The code hangs because you are accessing Result property of a Task. You should instead use await keyword to get the result from the Task.

    The deadlock happens because the synchronization context is captured by two different threads. See this answer for more details: await vs Task.Wait - Deadlock?

    It works in console application because SynchronizationContext.Current is null so there is no deadlock happening. See this post for more details: Await, SynchronizationContext, and Console Apps