Xamarin Forms 因异步 Http 调用而崩溃

Rom*_* Eh 0 c# async-await xamarin.forms xamarin-forms-4

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

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

仅在输出中收到此消息:

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)
Run Code Online (Sandbox Code Playgroud)

这是代码:

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;
Run Code Online (Sandbox Code Playgroud)

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

任何想法来解决这个问题?

Jac*_*Hua 12

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

  1. 在返回类型为 Task 的方法中等待使应用程序崩溃
  2. xamarin-android/问题
  3. xamarin-ios/问题

解决方法是使用GetAwaiter().GetResult()代替await

作品:

response = _client.GetAsync(uri).GetAwaiter().GetResult();
Run Code Online (Sandbox Code Playgroud)

不起作用:

await _client.GetAsync(uri);
Run Code Online (Sandbox Code Playgroud)