【发布时间】:2018-02-24 22:33:38
【问题描述】:
我想使用 Xamarin 执行下一步:
当应用程序启动时会立即显示 splashScreen(我已经在下一个教程 https://channel9.msdn.com/Blogs/MVP-Windows-Dev/Using-Splash-Screen-with-Xamarin-Forms 中实现了这一点)
执行数据库迁移(如果有)(以防用户更新应用并首次运行)
从 db 读取用户数据(用户名和密码),调用 REST web 服务检查用户数据是否仍然有效。如果用户数据有效,则将用户重定向到 MainPage,否则重定向到 LoginPage
我已经阅读了关于Xamarin.Forms Async Task On Startup 的下一篇好文章。当前代码:
public class MainActivity :global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new App ()); // method is new in 1.3
}
}
// shared code - PCL lib for Android and iOS
public partial class App : Application
{
public App()
{
InitializeComponent();
// MainPage = new LoadingPage();
}
}
protected override async void OnStart()
{
// Handle when your app starts
await App.Database.Migrations();
if( await CheckUser()) // reads user data from db and makes http request
this.MainPage = new Layout.BrowsePage();
else
this.MainPage = new LoginPage();
}
如果 MainPage 未在构造函数中设置,则在 iOS 和 Android 上将引发异常。我知道如果 async void 没有明确具有.Wait(),它不会等待 -
Async void,但这是否意味着正在执行的线程仍在继续它的工作。
当执行线程遇到await App.Database.Migrations(); 时,它会暂停执行并等待等待任务完成。同时它继续它的工作(即 LoadApplication() 继续执行并期望 App.MainPage 现在已设置)。我的假设是否正确?
我只是想避免LoadingPage,因为显示了三个屏幕:
- 启动画面(应用启动时正确)
- LoadingPage(数据库迁移、http 请求、..)
- BrowsePage 或 LoginPage
为了用户体验,最好只有两页。
我最终是这样的,但我相信有更好的方法:
protected override void OnStart()
{
Page startPage = null;
Task.Run(async() =>
{
await App.Database.Migrations();
startPage = await CheckUser() ? new Layout.BrowsePage() : new LoginPage();
}.Wait();
this.MainPage = startPage();
}
【问题讨论】:
-
您在寻找什么“更好的方法”?为什么你认为显示加载页面是一种低劣的用户体验?
-
我想如果应用程序需要 5-8 秒来加载,那么加载页面就可以了。它向用户显示正在发生的事情(正在进行的迁移,...)。我测量了时间,启动应用程序需要 7 秒(三星 Galaxy A5)。
标签: c# multithreading xamarin xamarin.forms async-await