从Xamarin PCL调用REST API时程序挂起

3
我在我的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));
        }
    }

我的程序在这一行卡住了

var response = await client.GetAsync(endpoint);

没有任何异常抛出。
我在控制台应用程序中执行了相同的代码,它可以正常工作。
唯一的区别是,在我的控制台应用程序中,我将 Newtonsoft.Json.dll 引用到 lib\net45 文件夹中。在我的 Xamarin PCL 项目中,我将 Newtonsoft.Json.dll 引用到 lib\portable-net40+sl5+wp80+win8+wpa81 文件夹中。我尝试引用位于 lib\portable-net45+wp80+win8+wpa81+dnxcore50 文件夹中的 dll,结果相同。
我正在使用 Json 8.0.3 版本。
2个回答

2
代码挂起是因为您正在访问Task的Result属性。您应该使用await关键字从Task获取结果。
死锁发生是因为同步上下文被两个不同的线程捕获。有关更多详细信息,请参见此答案:await vs Task.Wait - Deadlock? 它在控制台应用程序中工作是因为SynchronizationContext.Current为空,因此没有死锁发生。有关更多详细信息,请参见此帖子:Await、SynchronizationContext和Console Apps

2
您正在通过访问Result属性,强制在同步方法中运行异步操作。
public async Task<Product> Product(int id)
{

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

修改产品方法如上所述将修复它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接