IDispatcherTimer timer not stopping in timer.stop();

Heinz Deubler 181 Reputation points
2023-02-12T05:24:27.53+00:00

In this MAUI.NET app below the timer doesn't stop on timer.stop();

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ButtonTimer.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                x:Name="CounterBtn"
                Text="Start"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

using System.Diagnostics;

namespace ButtonTimer;

public partial class MainPage : ContentPage
{
	int count = 0;
    IDispatcherTimer timer;


    public MainPage()
	{
		InitializeComponent();
	}

    
    private void OnCounterClicked(object sender, EventArgs e)
	{
        timer = Application.Current.Dispatcher.CreateTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += (s, e) => Go();

        if (CounterBtn.Text == "Start")
		{
            timer.Start();
			CounterBtn.Text = "Stop";
		}
		else
		{
            timer.Stop();
            CounterBtn.Text = "Start";
        }

	}
    public void Go()
    {
        Debug.WriteLine("Ping");
    }
}

.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
4,006 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 120.4K Reputation points
    2023-02-12T07:05:30.7233333+00:00

    Try this:

    . . .
    public MainPage( )
    {
        InitializeComponent( );
    
        timer = Application.Current.Dispatcher.CreateTimer( );
        timer.Interval = TimeSpan.FromSeconds( 1 );
        timer.Tick += ( s, e ) => Go( );
    }
    
    private void OnCounterClicked( object sender, EventArgs e )
    {
        if( CounterBtn.Text == "Start" )
        {
    . . .
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.