Xamarin Forms 因异步 Http 调用而崩溃

Xamarin Forms crash with async Http call

我正在开发一个 Xamarin.Forms (4.1.0) 应用程序,它进行 REST 调用。

调用我的网络服务时,应用程序崩溃,无一例外。

在输出中只得到这条消息:

07-08 19:09:04.792 F/        (22723): * Assertion at /Users/builder/jenkins/workspace/xamarin-android-d16-1/xamarin-android/external/mono/mono/mini/debugger-agent.c:4387, condition `is_ok (error)' not met, function:get_this_async_id, Could not execute the method because the containing type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[RestQueryResultT_REF]', is not fully instantiated. assembly:<unknown assembly> type:<unknown type> member:(null)
07-08 19:09:04.793 F/libc    (22723): Fatal signal 6 (SIGABRT), code -6 (SI_TKILL) in tid 22723 (io.puffix), pid 22723 (io.puffix)

代码如下:

RestQueryResultT queryResult;

using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(serviceUri))
{
    string result = await response.Content.ReadAsStringAsync();
    queryResult = ParseResult(result);
}

return queryResult;

调用是从事件处理程序方法进行的,由 UI 操作触发。 GetAsync 调用导致应用程序崩溃。

有解决此问题的想法吗?

这似乎是一个问题,并且已在 Github 中归档。您可以在这些线程中看到讨论:

  1. await within method with returntype Task makes app crash
  2. xamarin-android/issues
  3. xamarin-ios/issues

解决方法是使用 GetAwaiter().GetResult() 而不是 await:

作品:

response = _client.GetAsync(uri).GetAwaiter().GetResult();

无效:

await _client.GetAsync(uri);

你能试试小一点的回应吗?我遇到了同样的问题(在我的例子中,当我使用来自服务器的 2 或 3 条记录进行测试时,它工作正常,但如果我使用 10 条记录,它就会崩溃)。我不得不改变模拟器。我现在正在使用我的 phone 连接到我的计算机。