Forms因异步Http调用而崩溃

Forms因异步Http调用而崩溃

本文介绍了Xamarin Forms因异步Http调用而崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Xamarin.Forms(4.1.0)应用程序,该应用程序可以进行REST调用.

I am developing a Xamarin.Forms (4.1.0) app, which makes REST calls.

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

When calling my web service, the application crashes, with no exception.

仅在输出上显示此消息:

Only got this message on the output:

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调用使应用程序崩溃.

The call is made from an event handler method, fired by a UI action.The GetAsync call made tha app crashes.

有解决这个问题的主意吗?

Any idea to solve this issue ?

推荐答案

这似乎是一个问题,已经在 Github 中提出.您可以在以下主题中查看讨论:

This seems a issue and already filed in the Github. You can see the discussions in these threads:

  1. 在带有returntype Task的方法内等待会导致应用崩溃
  2. xamarin-android/issues
  3. xamarin-ios/issues

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

The workaround is using GetAwaiter().GetResult() instead of await:

作品:

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

不起作用:

await _client.GetAsync(uri);

这篇关于Xamarin Forms因异步Http调用而崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 00:17