从异步方法使用视图上的数据

using data on the view from async method

我正在使用地理定位器插件来检索我的当前位置并向页面添加图钉。这是为此提供的服务:

tasks.cs

public async Task<Plugin.Geolocator.Abstractions.Position> GetDeviceCurrentLocation()
{
    try
    {
        var locator = Plugin.Geolocator.CrossGeolocator.Current;
        locator.DesiredAccuracy = 50;

        var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1));

        if (position != null)
        {
            return position;
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("Unable to get location, may need to increase timeout: " + ex);
    }

    return new Plugin.Geolocator.Abstractions.Position();
}

我正在尝试在这样的视图中使用它:

public MapPage(List<Models.xxx> xxx, Models.yyy yyy )
{
  InitializeComponent();
  Tasks ts = new Tasks();
  var myLocation = ts.GetDeviceCurrentLocation();
  var latitudeIm = myLocation.Result.Latitude;
  var longitudeIm = myLocation.Result.Longitude;
  var pin1 = new Pin
  {
    Type = PinType.Place,
    Position = new Position(latitudeIm, longitudeIm),
    Title = "My Location"
  };
  customMap.Pins.Add(pin1);
}

当我尝试此代码时我的应用程序中断 var latitudeIm = myLocation.Result.Latitude; 我想因为我有一个异步任务,所以结果必须是 awaited。知道如何在我的视图中使用 public async Task<Plugin.Geolocator.Abstractions.Position> GetDeviceCurrentLocation() 数据吗?

您应该使用 await 作为异步方法;

var myLocation = await ts.GetDeviceCurrentLocation();
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;

您应该将所有方法完全修饰为async。如果你不能应用它(我不推荐它),你可以使用 ConfigureAwait 来防止死锁;

var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false);

var myLocation = ts.GetDeviceCurrentLocation().Result;//Also don't hit the Result twice
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;