首页 > 解决方案 > 如何在按钮单击时停止 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
    }

标签: c#xamarinxamarin.forms

解决方案


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


推荐阅读