如何获取一个方法的值async c# windows phone 8.1
本文关键字:async windows phone 一个 何获取 获取 方法 | 更新日期: 2023-09-27 18:17:26
我有以下代码
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");
}
}
但是我需要在相同的方法中做,而不需要异步方法返回值,我肯定会以某种方式告诉我所有的异步方法停止获取这些值
我的问题是,当我打印经度和纬度零抛出我,因为异步方法发送的值肯定不是准时的。
谢谢
好的,首先你需要知道你不应该使用async void。这是一个允许您在其内部使用await的结构,但是如果您等待getLocation1(),您的程序将不会等待它。相反,您应该在可能的情况下始终使用异步任务。因此,请尝试将getLocation1更改为async Task,然后,当您等待它时,之后您将确定其中完成的任务。