c# - 我想从我的 OnAppearing() 开始每分钟运行一个方法。我需要将其作为任务运行吗?
问题描述
这是我想出的代码。它似乎有效,但我担心这可能不是做我想做的事的好方法。我需要的是在 OnAppearing 发生后每分钟运行一个方法,并让它随着 OnDisappearing(); 停止。
protected async override void OnAppearing()
{
base.OnAppearing();
BindingContext = vm;
cts = new CancellationTokenSource();
if (Settings.mode == MO.Practice)
{
if (!App.stopWatch.IsRunning) { App.stopWatch.Start(); }
Device.StartTimer(new TimeSpan(0, 0, 5), () =>
{
if (App.stopWatch.IsRunning && App.stopWatch.Elapsed.Seconds >= 60)
{
// Here's the method I want to run. After it's finished
// I call BeginInvoke .. to update info on the screen
if (App.DB.ReducePoints() == true)
Device.BeginInvokeOnMainThread(() =>
{
vm.PifInfo = GetPifInfo();
});
App.stopWatch.Restart();
}
return true;
});
}
await GetCards(cts.Token);
}
}
protected override void OnDisappearing()
{
Unsubscribe();
cts.Cancel();
if (App.stopWatch.IsRunning) { App.stopWatch.Stop(); }
base.OnDisappearing();
}
不是问题的一部分,但我也欢迎对代码发表任何评论。
解决方案
Device.StartTimer
您可以通过从、 重复true
、 不重复false
和不使用返回正确值来更简单地执行此操作StopWatch
。(来源声明,While the callback returns true, the timer will keep recurring.
正如您从源代码中看到的那样,该方法不需要 aFunc<Task<bool>>
它只需要一个Func<bool>
回调,因此不需要使用 a Task
。)
在课堂里
volatile bool run;
在出现
run = true;
Device.StartTimer(new TimeSpan(0, 1, 0), () => {
if (run) { /*do what you want;*/ return true; }
else { return false; }
});
在 OnDisappearing
run = false;
编辑 - 根据 OP 的要求
这是代码。我留下我原来的答案来帮助其他需要这个的人。
volatile bool run;
protected async override void OnAppearing()
{
base.OnAppearing();
BindingContext = vm;
cts = new CancellationTokenSource();
if (Settings.mode == MO.Practice)
{
run = true;
Device.StartTimer(new TimeSpan(0, 1, 0), () =>
{
if (run)
{
if (App.DB.ReducePoints() == true)
Device.BeginInvokeOnMainThread(() =>
{
vm.PifInfo = GetPifInfo();
});
return true;
}
else { return false; }
});
await GetCards(cts.Token);
}
}
protected override void OnDisappearing()
{
run = false;
Unsubscribe();
cts.Cancel();
base.OnDisappearing();
}
推荐阅读
- azure - 如何以编程方式将 DigiCert 作为证书颁发机构添加到 Azure Key Vault?
- node.js - AWS elasticsearch 服务:Curl http 命令工作正常,但不是 elasticsearch npm
- pine-script - Pinescript:想在不使用安全功能的情况下获得前一天的高点
- java - Bytedeco.javacv.FFmpegFrameGrabber 问题
- python-3.x - Django rest framework merging two serializers data based on following requirement
- javascript - Three.js:用一种颜色填充网格着色器材料到某个位置
- python - pyodbc 在 MS SQL 服务器中使用二进制数据更新记录
- kotlin - 如何在 Kotlin 中将值从函数传递到另一个函数?
- java - 模拟方法中的依赖项而不是方法本身
- python - Python 字符串通过套接字发送两次