我有两种方法:
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;
}
和
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());
}
在构造函数中我有这样的东西:
public NearbyControlViewModel()
{
var test = CenterMapOnMyLocation();
GetClosestLocations(test);
}
现在,我的问题是,当在构造函数中调用第二个方法时,“test”变量还没有初始化……因为它是异步的。我想要做的是等待它被初始化,然后调用第二种方法。如果我从异步方法调用我的第二个方法,我会得到一个异常: InvalidOperationException - 集合处于不可写模式。“Treks”值绑定到 MapItemsControl。所以我猜想关于线程的问题。