【问题标题】:How to stop device.starttimer xamarin forms on button click?如何在按钮单击时停止 device.starttimer xamarin 表单?
【发布时间】:2018-10-15 22:18:50
【问题描述】:

所以我有两个按钮 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
    }

【问题讨论】:

  • 当您从 Func 返回 false 时,计时器停止。
  • 这就是我的想法,但是当我声明 shouldRun = false 时,停止按钮不起作用。
  • 在停止按钮中声明 shouldRun = false 后,如果您不希望将标签设置为“时间到了”,则计时器委托将在其 3 秒计时器结束时再运行一次!",那么您需要在此之前检查shouldRun 并跳过该分配(或提前退出,return false)。

标签: c# xamarin xamarin.forms


【解决方案1】:
  1. 您将取消令牌源添加到运行计时器的视图中

    私人 CancellationTokenSource 取消;

  2. 如下调整您的 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;
    }
    
  3. 最后在您的计时器委托中创建取消令牌源

    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 在他的评论中提到。然而,取消源是线程安全的,因此当您从不同的线程停止计时器时,您不会遇到令人讨厌的竞争条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2020-04-11
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多