别让你的WP7应用启动速度超过5秒

最近在调试一个Windows Phone 7的应用,在模拟器和真机上联机调试正常。部署到真机实际使用时,偶尔会发现程序在启动时自动退出。后来在程序中加入了启动时的debug信息发现,如果启动时间超过5秒,程序会自动退出。原来,我的应用需要在每天第一次启动时整理数据,删除过期的数据。有时由于过期数据量大而导致启动时间超过5秒。
查阅windows phone 7认证要求, 在《Windows Phone 7 Application Certification Requirements》的5.2.1 Launch Time中写到

  • The application must render the first screen within 5 seconds after launch.应用程序在启动后5秒之内必须显示第一个页面(这个第一个页面不是Splash Image).
  • The application may provide a splash screen image in a file called SplashScreenImage.jpg in the root of the XAP package while the application is still trying to load.
  • Within 20 seconds after launch, the application must be responsive to user input(应用在启动20秒之内能够开始响应用户操作).

也就是说,我的应用有时启动时会超过5秒,系统自动阻止了程序的启动。
查阅MSDN文档Windows Phone 性能Performance Considerations in Applications for Windows Phone,在应用程序启动Application Startup一节中找到了解决方案:

即启动一个新线程执行耗时的操作:

using System.Threading;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//在一个新线程中进行耗时操作,让UI界面能够响应用户操作
System.Threading.Thread startupThread =
new System.Threading.Thread(new System.Threading.ThreadStart(initializePage));
startupThread.Start();
}
void initializePage()
{
// 耗时操作代码...
}

   还有一个方法就是在后台执行一些耗时的初始化,执行完毕后在主线程中更新UI.

using System.Threading;
using System.ComponentModel;
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s,e) =>
{
// 启动一个后台线程
};
backgroundWorker.RunWorkerCompleted +=
(s, e) =>
{
// 后台线程结束后,还需要执行的操作
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//这段代码用于更新UI等需要在主线程中进行的操作
});
};
backgroundWorker.RunWorkerAsync();
This entry was posted in Window Phone 7, 未分类. Bookmark the permalink.

2 Responses to 别让你的WP7应用启动速度超过5秒

  1. 现在还习惯于XP,有时间向博主交流学习下。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>