c# - How can I wait for await to finish and only then continue? -
i have 2 methods:
private async task<geocoordinate> centermaponmylocation() { geolocator mygeolocator = new geolocator(); geoposition mygeoposition = await mygeolocator.getgeopositionasync(); geocoordinate mygeocoordinate = mygeoposition.coordinate; geocoordinate mygeocoordinate = convertgeocoordinate(mygeocoordinate); mapcenter = mygeocoordinate; if (mylocation.latitude == 0 && mylocation.longitude == 0) { mylocation = mapcenter; } return mygeocoordinate; } and
private void getclosestlocations(geocoordinate mylocation) { var locations = new observablecollection<pushpinmodel> { new pushpinmodel { location = new geocoordinate(51.569593, 10.103504), locationname = "1" }, new pushpinmodel { location = new geocoordinate(-45.569593, 1.103504), locationname = "2" }, new pushpinmodel { location = new geocoordinate(0, 0), locationname = "3" } }; foreach (var location in locations) { location.distancetomylocation = haversinedistance(mylocation, location.location); } treks = new observablecollection<pushpinmodel>(locations.orderby(l => l.distancetomylocation).take(2).tolist()); } and in constructor have this:
public nearbycontrolviewmodel() { var test = centermaponmylocation(); getclosestlocations(test); } now, problem when second method called in constructor, "test" variable not initialized yet... because it's async. want wait initialized , after call second method. if call second method async method exceptions: invalidoperationexception - collection in non writeable mode. "treks" value binded mapitemscontrol. guess problem threads.
you need use asynchronous initialization. give few different solutions in blog post on async construction.
note asynchronous code forces have better ui design. i.e., must design kind of "before map centered" state ui. ui start in state, , when (asynchronous) initialization complete, ui updated.
Comments
Post a Comment