wp8中async和await的问题

本文关键字:问题 await async wp8 | 更新日期: 2023-09-27 18:15:10

我正在启动位置设置,如果它被禁用,并试图使用下面的代码获得当前位置。

    if (locator.LocationStatus == PositionStatus.Disabled)
        {
            MessageBox.Show("Please enable the Location services", "Alert", MessageBoxButton.OK);
            await Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
        }
        if (locator.LocationStatus == PositionStatus.Ready)
        {
            Geoposition geoposition;
            Geocoordinate geocoordinate;
            GeoCoordinate geoCor = null;
            geoposition = await locator.GetGeopositionAsync();
            geocoordinate = geoposition.Coordinate;
            geoCor = CoordinateConverter.ConvertGeocoordinate(geocoordinate);
            ReverseGeocodeQuery reverseQuery = new ReverseGeocodeQuery
            {
                GeoCoordinate = geoCor
            };
        }

一旦"await"被执行,它就会转移到下一条语句。所以没有得到正确的结果。我知道等待将异步工作,但接下来的语句是基于一个等待结果吗?

geoposition = await geolocator.GetGeopositionAsync();
            geocoordinate = geoposition.Coordinate;
            geoCor = CoordinateConverter.ConvertGeocoordinate(geocoordinate);
            ReverseGeocodeQuery reverseQuery = new ReverseGeocodeQuery
            {
                GeoCoordinate = geoCor
            };
            reverseQuery.QueryCompleted += (s, e) =>
                {
                    if (e.Error != null)
                        return;
                    if (e.Result != null && e.Result.Count > 0 && e.Result[0].Information != null && e.Result[0].Information.Address != null)
                        city = e.Result[0].Information.Address.City;
                };
            reverseQuery.QueryAsync();
            this.mapWithMyLocation.Center = geoCor;
            this.mapWithMyLocation.ZoomLevel = 10;

显示正确的地理坐标…但是没有得到地址

wp8中async和await的问题

如果我理解对了你的问题,那么你应该注意位置变化事件或指定所需的报告间隔。例如:

{
    ...
    locator.DesiredAccuracy = PositionAccuracy.High;
    locator.MovementThreshold = 5d;
    // locator.ReportInterval = (uint)TimeSpan.FromSeconds(5).TotalMilliseconds; 
    locator.PositionChanged += RaiseLocationChanged;
    ...
}
private void RaiseLocationChanged(Geolocator sender, PositionChangedEventArgs args)
{
    // Your reverse geocode etc. logic might go here...
    var location = CoordinateConverter.ConvertGeocoordinate(args.Position.Coordinate);
}