正确的方式以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.
值得注意的是,OnAppearing
和OnDisappearing
并非总是在不同平台上同时一致地被调用.例如,如果您在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.