0

I'm learning C# at the moment, and to do so I decided to make a clicker game using WPF on Visual Studio. I'm trying to add a button that automatically gives you coins per second once clicked. I've tried multiple methods of getting an infinite loop to work which usually resulted in the program's refusal to even start.

The closest I've gotten to something that works is this code.

public void Timer_Start()
{
    Timer timer = new Timer(Tick, null, 100, 1000);
}

public MainWindow()
{
    InitializeComponent();
    Timer_Start();
}

public void Tick(object stateInfo)
{
    coins += cps;
    //MessageBox.Show("Running");
    this.Dispatcher.Invoke(() =>
    {
        Score_Update();
    });
}

However, when I run this code, it only works for about 1 or 2 seconds before stopping. The amount of times it runs varies between 1 and 10.

3
  • 6
    Assign created timer to class field. It just removed by Garbage Collector. Commented Jun 9, 2022 at 2:33
  • Does this answer your question? How do I create a timer in WPF? Commented Jun 9, 2022 at 8:22
  • System.Threading.Timer is a tricky class. If you don't keep a reference to it then the garbage collector is allowed to destroy the object. Passing this as the second argument to the constructor is another way to keep it alive at least as long as the window. But realistically, you really want to use a DispatcherTimer here. Stays alive until you Dispose() it, and avoids the need to use Dispatcher.Invoke(). Commented Jun 9, 2022 at 9:20

1 Answer 1

0

juste replace your "timer_start" method and your constructor with this :

        private Timer timer;

    public MainWindow()
    {
        InitializeComponent();

        this.timer = new Timer(Tick, null, 100, 1000);
    }

This way, your timer instance is not cleaned by .net. Remeber to stop/dispose it on window close or application exit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.