【问题标题】:using data on the view from async method通过异步方法使用视图上的数据
【发布时间】:2018-01-16 11:04:19
【问题描述】:

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

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&lt;Plugin.Geolocator.Abstractions.Position&gt; GetDeviceCurrentLocation() 数据吗?

【问题讨论】:

    标签: c# asynchronous xamarin xamarin.forms geolocation


    【解决方案1】:

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

    【讨论】:

    • 我不能等待 ts.GetDeviceCurrentLocation() 。见编辑。我应该创建一个模型吗?只有纬度和经度属性?你是什​​么意思控制器?我在项目中没有控制器。我没有使用 MVC 模式。
    • 我无法使用var myLocation = await ts.GetDeviceCurrentLocation() 这一行,因为我试图访问页面构造函数上的数据并且它不是异步的,这就是为什么它会给我一个错误。如果我可以使用等待,那么问题将得到解决。 ://
    • 那么,你可以使用“ConfigureAwait”。
    • 我试过了,但仍然是死锁情况,应用程序仍然中断。还有其他方法吗?还有其他方法吗?
    • 您是否尝试删除 ConfigureAwait 并应用 Task.Run; “Task.Run(() => ts.GetDeviceCurrentLocation()).Result;”但正如我所说,这不是一个好习惯。完全异步地装饰你的方法可能会更好。
    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2023-03-21
    • 2015-12-02
    • 1970-01-01
    • 2018-12-14
    • 2020-02-10
    • 2021-02-06
    相关资源
    最近更新 更多