我有这个代码,我的意图是,当应用程序打开时,它将运行一个名为PointChecker.CheckPoints()的方法;每一分钟. 此方法与db2.Execute(“UPDATE ….. etc”)同步对我的数据库运行更新; 据我所知,阅读本文
此方法与db2.Execute(“UPDATE ….. etc”)同步对我的数据库运行更新;
据我所知,阅读本文:
https://xamarinhelp.com/xamarin-forms-async-task-startup/
我可以通过几种不同的方式实现这一点.
我想知道的是,如果运行这样的代码存在任何性能问题,如果我要以不同的方式运行它,可以减少这些问题.特别是最近有任何Xamarin.Forms工作方式的改变(我的应用程序在iOS和Android上通过Forms运行),我应该考虑,这可能会导致更好的方式来完成这项任务.
public App() {
InitializeComponent();
DB.PopulateTables();
MainPage = new Japanese.MainPage();
}
protected override async void OnStart() {
await Task.Run(() => {
StartTimer();
});
}
public void StartTimer() {
if (!stopWatch.IsRunning)
stopWatch.Start();
Device.StartTimer(new TimeSpan(0, 0, 1), () => {
if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes >= 1) {
PointChecker.CheckPoints();
stopWatch.Restart();
}
return true;
});
}
protected override void OnSleep() {
stopWatch.Reset(); base.OnSleep();
}
protected override void OnResume() {
base.OnResume(); stopWatch.Start();
}
最近对Xamarin的更改不应该影响这一点.这种方法是最有效的方法.我唯一要考虑的是为什么你的方法需要异步.你可以打电话:
protected override void OnStart()
在another thread中讨论了一个非UI阻塞的解决方案:
using Xamarin.Forms;
using System;
using System.Linq;
using System.Diagnostics;
namespace YourNamespace
{
public partial class App : Application
{
private static Stopwatch stopWatch = new Stopwatch();
private const int defaultTimespan = 1;
protected override void OnStart()
{
// On start runs when your application launches from a closed state,
if (!StopWatch.IsRunning)
{
StopWatch.Start();
}
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
// Logic for logging out if the device is inactive for a period of time.
if (StopWatch.IsRunning && StopWatch.Elapsed.Minutes >= defaultTimespan)
{
//prepare to perform your data pull here as we have hit the 1 minute mark
// Perform your long running operations here.
InvokeOnMainThread(()=>{
// If you need to do anything with your UI, you need to wrap it in this.
});
stopwatch.Restart();
}
// Always return true as to keep our device timer running.
return true;
});
}
protected override void OnSleep()
{
// Ensure our stopwatch is reset so the elapsed time is 0.
StopWatch.Reset();
}
protected override void OnResume()
{
// App enters the foreground so start our stopwatch again.
StopWatch.Start();
}
}
}
最重要的是,这种方法是
Platform agnostic
