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

时间:2018-01-16 11:04:19

标签: c# asynchronous xamarin xamarin.forms geolocation

我使用geolocator插件检索我当前的位置并在页面上添加一个图钉。以下是此项服务:

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() 数据?

1 个答案:

答案 0 :(得分:3)

您应该使用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;