我有以下代码
async void getLocation1()
{
try {
var geolocator = new Geolocator();
Geoposition position = await geolocator.GetGeopositionAsync();
// reverse geocoding
BasicGeoposition myLocation = new BasicGeoposition
{
Longitude = position.Coordinate.Longitude,
Latitude = position.Coordinate.Latitude
};
Geopoint pointToReverseGeocode = new Geopoint(myLocation);
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);
// here also it should be checked if there result isn't null and what to do in such a case
PostalCode1 = result.Locations[0].Address.PostCode;
Country1 = result.Locations[0].Address.Country;
City1 = result.Locations[0].Address.Town;
State1 = result.Locations[0].Address.Region;
guardarLatit = myLocation.Latitude.ToString();
guardarLong = myLocation.Longitude.ToString();
await GeolocationWait();
MessageDialog msgbox3 = new MessageDialog("Latitud: " + guardarLatit + "Longitud: " + guardarLong);
MessageDialog msgbox4 = new MessageDialog("PostalCode: " + PostalCode1 + " Country: " + Country1 + "City: " + City1 + "State: " + State1);
geolocation.Add("Latitud: " + guardarLatit);
geolocation.Add("Longitud: " + guardarLong);
geolocation.Add("PostalCode: " + PostalCode1);
geolocation.Add("Country: " + Country1);
geolocation.Add("City: " + City1);
geolocation.Add("State: " + State1);
await msgbox3.ShowAsync();
await msgbox4.ShowAsync();
} catch (Exception ex)
{
MessageDialog msgboxE = new MessageDialog("Error");
await msgboxE.ShowAsync();
geolocation.Add("Latitud: null");
geolocation.Add("Longitud: null");
geolocation.Add("PostalCode: null");
geolocation.Add("Country: null");
geolocation.Add("City: null");
geolocation.Add("State: null");
}
}
但我需要在没有异步方法返回值的同一方法中执行它我当然会以某种方式告诉我所有异步它停止获取该值。
我的问题是,当我打印经度和纬度零时,由于异步方法确实不能按时发送值,因此抛出了我。
谢谢
答案 0 :(得分:0)
好的,首先你需要知道你不应该使用async void。 它是一种允许你在其中使用await的结构,但如果你等待getLocation1(),你的程序将不会等待它。 相反,您应该始终使用异步任务。因此,请尝试将getLocation1更改为异步任务,然后,当您等待它时,之后您将确定其中已完成的任务。