Problems with the async/wait concept

Hi,

I'm just starting with Xamarin, been a part time C# but never used the async/wait functionality.
So I tried to use some plugin's with very mixed results.
Take in account that I'm calling these methods at the startup of the application in App.xaml.cs.
So that's not an aync event, it's just a plain old event.

I'm using Xamarin 4.7.10 with Xamarin Android 8.0.2.1 in VS.Net 2015 U3, using a AVD Nexus 4 Android 7.1.1 Intel Atom x86.

First of all the Permissions plugin, I want to check and get the permission to use the location (GPS).
The below function should return true if I have the permission but return false if the permission is not given (after asking for it).
So it can detect the permission status and even asks for the permission if necessary.

However my result.Wait() function ,which if I understand correctly should wait until the async call has been completed, never completes.
I do get the popup asking for the permissions but when I close the popup (either deny or approve), my code does not continue.

private static bool RequestLocationPermission()
{
try
{
var status = CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
status.Wait();

            if (status.Result != PermissionStatus.Granted)
            {
                var results = CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });
                results.Wait();

                if (results.Result[Permission.Location] == PermissionStatus.Granted)
                    return true;
                else
                    return false;
            }
            else
                return true;

        }
        catch (Exception ex)
        {

            return false;
        }
    }
}

I got another strange behavoir, trying to get the GeoLocation with the Geolocator.
Again within a normal function (not an async one) but here the .Wait crashes the app.
No call stack, only a 'An unhandled exception occured.', breaking shows no code because all threads were executing external code.

var locator = CrossGeolocator.Current;
if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled)
{
var location = locator.GetPositionAsync(new TimeSpan(5000));
location.Wait();

            if (location != null && location.IsCompleted && location.Result != null)
            {
                this.Longitude = location.Result.Longitude;
                this.Latitude = location.Result.Latitude;
            }

        }

Might be that my approach or my understanding on the whole async method call, is totally off.
Anybody got some advice or tips to get this code working?

Regards,
Sven Peeters

Sign In or Register to comment.