简体   繁体   English

Xamarin.Forms异步/等待操作不起作用

[英]Xamarin.Forms async/ await operations not working

I have a simple Xamarin.android mobile app which is getting data from API hosted in local PC. 我有一个简单的Xamarin.android移动应用程序,该应用程序从本地PC中托管的API获取数据。 Problem is when I run the app it will not get the result as expected. 问题是,当我运行该应用程序时,不会获得预期的结果。

_client is a HttpClient and I'm able to visit the same URL from emulator's browser and get the data. _client是一个HttpClient,我可以从模拟器的浏览器访问相同的URL并获取数据。 Following is my code. 以下是我的代码。

 protected async override void OnAppearing()
    {
        string content = await _client.GetStringAsync("http://192.168.10.101:1001/api/todo");
        base.OnAppearing();
    }

once I hit F5 emulator is firing up and running the app but it's not getting any data. 一旦我按下F5,模拟器就会启动并运行该应用程序,但没有获取任何数据。 Also when I debugging, once I hit the F10, await statement will execute an application will continue and will not wait. 同样,当我调试时,一旦我按下F10,await语句将执行,应用程序将继续执行并且不会等待。

Does anyone have any idea about this issue? 有没有人对此问题有任何想法?

I'm using API version 9, level 28 and visual studio 2019 Thanks. 我正在使用API​​版本9,级别28和Visual Studio 2019谢谢。

From the official documentation for await keyword: 从官方文档中的await关键字:

The await operator suspends execution until the work of the method is complete. 等待操作符将暂停执行,直到该方法的工作完成为止。 In the meantime, control is returned to the caller. 同时,控制权返回给调用者。 When the task finishes execution, the await expression evaluates to... 当任务完成执行时,await表达式的计算结果为...

What this means is that in some cases (I suspect in your's as well) at the time when the awaited method is executed the program is in a state where this does not matter anymore. 这意味着在某些情况下(我怀疑也在您的情况下),在执行等待的方法时,程序处于不再重要的状态。 If I am correct. 如果我是正确的。 Then you can work your way around this by using the Wait() or Result 然后,您可以使用Wait()Result来解决此问题

protected override void OnAppearing()
{
    string content = _client.GetStringAsync("http://192.168.10.101:1001/api/todo").Result;
    base.OnAppearing();
}

PS 聚苯乙烯

However, even if using Result works for you I suggest you to take more time looking into async/await and maybe come up with a better solution to the problem you are solving. 但是,即使使用Result适合您,我还是建议您花更多时间研究async/await ,也许可以针对您要解决的问题提出更好的解决方案。 This so answer is a good starting point. 因此,答案是一个很好的起点。

Issue is with the permission. 问题在于许可。 I haven't setup the permission or network security config in resources. 我尚未在资源中设置权限或网络安全配置。 It gave me an error after few seconds. 几秒钟后,它给了我一个错误。 Once i setup those things it worked fine. 一旦我设置了这些东西,它就可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM