所以我有两个按钮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
}
答案 0 :(得分:0)
您将取消令牌来源添加到运行计时器的视图中
私人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在其评论中提到。但是,取消来源是线程安全的,因此从其他线程停止计时器时,您不会遇到令人讨厌的竞争状况。