Reputation: 131
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;
}
Upvotes: 2
Views: 612
Reputation: 1213
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;
});
Upvotes: 4