正确的方式以Xamarin形式加载数据异步 [英] correct way to load data async in xamarin forms

查看:121
本文介绍了正确的方式以Xamarin形式加载数据异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正确加载异步数据的正确方法是什么,以便能够尽快向用户显示UI.例如

我有一个xamarin表单项目,其中包含一个地图组件. 我想先显示地图,然后再获取用户的当前位置(来自gps)以及从服务器获取的一些位置/管脚.我已经看到了这两种方法

I have a xamarin forms projekt, containing a map component. I want to show the map before I get the users current location(from gps) and some locations/pins that are fetched from a server. I have seen these two approaches

1)从构造函数中调用异步方法

1) From constructor call an async method

   Map mMyMap;
   ctor()
   {
       InitializeCompeont();
       InitAsync();
   }
   private async void InitAsync()
   { 
      var pins = await GetPinsFromServer();
      mMyMap.Pins.Add(pins)
   }

2)在出现中

 ctor()
  {
   InitalizeComponent()
  }
  protected override async void OnAppearing()
  { 
      var pins = await GetPinsFromServer();
       mMyMap.Pins.Add(pins)
   }

两个方法似乎都可以工作",但是我愚弄了自己从构造函数中调用async方法的方法吗?

Both approaces seems to "work", but Im I fooling myself calling the async method from constructor?

我也设法通过两种方式设置BindingContext异步,并且绑定正确

Ive also managed to set BindingContext async both ways and it binds correctly

有什么区别吗?

推荐答案

加载时间和调用数据的时间有所不同.如果在页面ctor中完成此操作,则在第一次创建该页面时将仅调用一次.

There is a difference in timing and when your load data will be called. If done in the page ctor it will be called once and only once when that page is first created.

如果在OnAppearing中完成,则调用将在显示页面之前进行,并且可以多次调用.例如,如果将另一个页面推到顶部然后将其弹出,则会再次调用OnAppearing重新加载您的数据,如果其他页面修改了上一页中显示的数据,则可以这样做.否则,您可能会进行不必要的加载数据调用.

If done in OnAppearing the call will happen prior to the page being shown and can be called more than once. For example, if you push another page on top of it and then popped it OnAppearing would get called again reloading your data, which might be okay to do if that other page modified the data being displayed on the previous page. Otherwise, you're potentially making unnecessary load data calls.

值得注意的是,OnAppearingOnDisappearing并非总是在不同平台上同时一致地被调用.例如,如果您在Android或iOS上使用内置共享,则一个事件可能会触发这两个事件,而另一个事件可能根本不会触发任何事件.

It is worth noting that OnAppearing and OnDisappearing aren't always consistently called at the same time on different platforms. For example, if you used the built-in sharing on Android or iOS one might fire both events, but the other might not fire any at all.

此外,我将确保您使用Task.Run();在后台线程上运行任何长时间运行的任务,以确保您没有锁定主线程,并可能设置了bool来显示/如果有必要,可以隐藏微调框,以了解后台任务的开始和结束时间.

Also, I'd make sure you're making use of Task.Run(); to run any long running tasks on a background thread, to ensure you're not locking up the main thread, and potentially set a bool to show/hide a spinner if necessary to know when your background task starts and ends.

这篇关于正确的方式以Xamarin形式加载数据异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆