c# - Xamarin Forms 因异步 Http 调用而崩溃
问题描述
我正在开发一个 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)
这是代码:
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
. 您可以在这些线程中看到讨论:
解决方法是使用GetAwaiter().GetResult()
而不是await
:
作品:
response = _client.GetAsync(uri).GetAwaiter().GetResult();
不工作:
await _client.GetAsync(uri);