简体   繁体   中英

How to create an infinite loop in C# using Threading.Timer in WPF

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM