c# - 如何在按钮单击时停止 device.starttimer xamarin 表单?
问题描述
所以我有两个按钮 Start/Stop 和 start 工作正常,因为每次单击 start 时它都会从头开始,这就是我想要的。但我是 xamarin 表单的新手,并不完全了解如何停止 device.starttimer。
这是我目前拥有的,但它不起作用。(不要担心声音的东西)
//timer
bool shouldRun = false;
private void timer()
{
Device.StartTimer(TimeSpan.FromSeconds(3), () =>
{
// Do something
label.Text = "Time is up!";
//shows start button instead of stop button
startButton.IsVisible = true;
//hides stop button
stopButton.IsVisible = false;
return shouldRun;
});
}
private void STOPButton_Clicked(object sender, EventArgs e)
{
//shows start button instead of stop button
startButton.IsVisible = true;
//hides stop button
stopButton.IsVisible = false;
//stops timer
shouldRun = false;
//stops sound
}
private void STARTButton_Clicked(object sender, EventArgs e)
{
//hides start button
startButton.IsVisible = false;
//shows stop button instead of start button
stopButton.IsVisible = true;
//starts timer from beginning
timer();
//starts sound from beginning
}
解决方案
您将取消令牌源添加到运行计时器的视图中
私人 CancellationTokenSource 取消;
如下调整您的 StopButton 代码:
private void STOPButton_Clicked(object sender, EventArgs e) { startButton.IsVisible = true; //hides stop button stopButton.IsVisible = false; //stops timer if (this.cancellation != null) Interlocked.Exchange(ref this.cancellation, new CancellationTokenSource()).Cancel(); shouldRun = false; }
最后在您的计时器委托中创建取消令牌源
CancellationTokenSource cts = this.cancellation = new CancellationTokenSource(); Device.StartTimer(TimeSpan.FromSeconds(3), () => { if (this.cancellation != null) Interlocked.Exchange(ref this.cancellation, new CancellationTokenSource()).Cancel(); // Do something label.Text = "Time is up!"; //shows start button instead of stop button startButton.IsVisible = true; //hides stop button stopButton.IsVisible = false; return shouldRun; });
基本上它与布尔标志方法非常相似,SushiHangover 在他的评论中提到。然而,取消源是线程安全的,因此当您从不同的线程停止计时器时,您不会遇到令人讨厌的竞争条件。
推荐阅读
- spring-boot - 我想获取 MongoTemplate 的 findAndModify 返回值作为修改值
- python - plotly px.scatter_3d 标记大小
- gdb - gdb 自动继续等待 ENTER?
- python - 在 Linux 上安装 pickle5 时出现终端错误
- javascript - 如何使用NodeJS替换作为Json对象值键的字符串
- webdriver - Codeception Webdrivers - 我可以在打开页面之前设置 cookie 吗?
- javascript - Vue 3:如何使用组合 API 正确更新组件道具值?
- vue.js - Vue 3 cli-service 应用程序:当从其他组件导入带有插槽的组件时,“插槽“默认”在渲染函数之外调用”警告
- airflow - 如何以少于 1 分钟的间隔运行 dag
- c# - 从字典中指定的类型转换为 IList 类型