简体   繁体   English

如何在 C# 中使用 WPF 中的 Threading.Timer 创建无限循环

[英]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.我现在正在学习 C#,为此我决定在 Visual Studio 上使用 WPF 制作一个点击游戏。 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.但是,当我运行此代码时,它仅在停止前大约 1 或 2 秒有效。 The amount of times it runs varies between 1 and 10.它运行的次数在 1 到 10 之间变化。

juste replace your "timer_start" method and your constructor with this : juste 用这个替换你的“timer_start”方法和你的构造函数:

        private Timer timer;

    public MainWindow()
    {
        InitializeComponent();

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

This way, your timer instance is not cleaned by .net.这样,您的计时器实例不会被 .net 清理。 Remeber to stop/dispose it on window close or application exit.请记住在窗口关闭或应用程序退出时停止/处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Threading.Timer在ASP.NET C#上的公共非静态方法上循环? - How to use Threading.Timer for a loop on a public non-static method on ASP.NET C#? 创建一个带有周期Timeout.Infinite的.NET Threading.Timer - Create a .NET Threading.Timer with a period Timeout.Infinite C#.NET 2 Threading.Timer - 时间漂移 - C# .NET 2 Threading.Timer - time drifting 使用带有Threading.Timer的锁 - Using lock with Threading.Timer C#Threading.Timer只会滴答一次 - C# Threading.Timer only ticks once 捕获倒计时或滴答事件 - Threading.Timer C# - Capture Countdown or Tick Event - Threading.Timer C# C#Async Ping:不能从Threading.Timer中工作 - C# Async Ping: not work from a Threading.Timer 如何在不使用System.Timers.Timer或System.Threading.Timer的情况下在C#中创建计时器 - How to create a timer in C# without using System.Timers.Timer or System.Threading.Timer C#线程:通过threading.timer创建一个comcomponent并从不同的threadingTimer实例处理相同的组件 - c# threading: creating a comcomponent via threading.timer and disposing of same component from a different threadingTimer instance C#重新启动Threading.Timer with Change不会停止初始Timer实例 - C# restarting Threading.Timer with Change does not stop initial Timer instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM