3

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

You are forcing the Async operation to be run in a synchronous method by accessing Result property

public async Task<Product> Product(int id)
{

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

Modifying Product Method as above will fix it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.