简体   繁体   中英

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. 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. 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. Also when I debugging, once I hit the F10, await statement will execute an application will continue and will not wait.

Does anyone have any idea about this issue?

I'm using API version 9, level 28 and visual studio 2019 Thanks.

From the official documentation for await keyword:

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...

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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