简体   繁体   中英

Xamarin.Forms Map doesn't get along with async await

When I try to add a pin to the map, the app halts. It doesn't continue executing the next piece of code. This happens only when I call DoWork from await; however not calling await doesn't not halt the app.

By halt, I mean it doesn't crash the application it just doesn't execute the next line of code yet I can still interact with the application.

Am I missing something or using async wrong?

Map myMap;
public MyViewModel(Map map)
{
    myMap = map;

    // Causes crash
    Task.Run(async () => 
    {
        await DoWork();
    });

    // Causes no crashes
    //DoWork();
}

async Task<bool> DoWork()
{
    var success = false;

    Task<bool> task = null;
    task = SomeTask();
    if (await task)
    {
        var pin = MyPin();      
        myMap.Pins.Add(pin);

        // This is never called when calling await Dowork(). Application stops.
        myMap.MoveToRegion(MapSpan.FromCenterAndRadius(MyPosition(), Distance.FromMiles(5)));
        success = true;
    }

    return success;
}

public Pin MyPin()
{
    var pin = new Pin();
    pin.Type = PinType.Place;
    pin.Position = new Position(<latitude>, <longitude>);
    return pin;
}

The problem here is that you need to execute MoveToRegion from the UI-Thread.

if running the task with Task.Run(() => ... you are invoking it on a background thread.

to make sure the ui manipulation is done on the mainthread you can force it

Device.BeginInvokeOnMainThread(() =>
{

  var pin = MyPin();      
    myMap.Pins.Add(pin);

    // This is never called when calling await Dowork(). Application stops.
    myMap.MoveToRegion(MapSpan.FromCenterAndRadius(MyPosition(), Distance.FromMiles(5)));
    success = true;
});

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