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.

burnsi
  • 6,194
  • 13
  • 17
  • 27
Yuri O
  • 1
  • 6
    Assign created timer to class field. It just removed by Garbage Collector. – Svyatoslav Danyliv Jun 09 '22 at 02:33
  • Does this answer your question? [How do I create a timer in WPF?](https://stackoverflow.com/questions/11559999/how-do-i-create-a-timer-in-wpf) – Pablo Caballero Jun 09 '22 at 08: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(). – Hans Passant Jun 09 '22 at 09:20

1 Answers1

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.

Romka
  • 144
  • 8