C#Timer - 在计时器运行时运行代码

时间:2018-05-02 11:22:14

标签: c# winforms timer

我是C#的新手,我正在尝试使用Windows Forms创建一个简单的大脑训练计划,这是我在学习Android App开发时学到的。我被卡在了计时器上。我有它的工作,它每秒触发并更新我的表单上的标签。当我启动计时器后添加代码时,计时器停止。这就像我不在后台运行。我已经阅读了许多关于线程计时器和计时器等的内容,但我还没有设法让任何工作。就像我说的,我是C#的新手,所以请温柔......他是我的代码......

public partial class BrainTrainer : Form
{
    // Set global timer variables & Create Timer
    static int secondCounter = 10;
    static bool play = false;
    static Timer myTimer = new Timer();


    public BrainTrainer()
    {
        // Set up form
        InitializeComponent();
        toggleLabels(false);
        timerLbl.Text = secondCounter.ToString() + "s";


    }

    // Function to loop through labels and disabled them
    private void toggleLabels(bool state)
    {
        var ansLabels = this.Controls.OfType<Label>()
            .Where(c => c.Name.StartsWith("ans"))
            .ToList();

        foreach (var label in ansLabels)
        {

            label.Enabled = state;
        }
    }

    // Event to run every second
    private void TimerEventProcessor(Object myObject, EventArgs e)
    {
        if (secondCounter == 0)
        {
            //Stop Game
            myTimer.Stop();
            play = false;

        }
        else
        {
            // Countdown 1 and update label
            secondCounter--;
            timerLbl.Text = secondCounter.ToString()+"s";
        }
    }

    private void startBtn_Click(object sender, EventArgs e)
    {
        // Hide button, set play to true and enable labels
        startBtn.Hide();
        play = true;
        toggleLabels(true);

        // Set up timer event, interval and start
        myTimer.Tick += new EventHandler(TimerEventProcessor);
        myTimer.Interval = 1000;
        myTimer.Start();
        // Run function to play
        genEquation();    

    }

    private void genEquation()
    {
        while (play)
        {
            Console.WriteLine(secondCounter);   
        }

    }

}

非常感谢任何帮助,或者指向有用教程的链接会很棒!

1 个答案:

答案 0 :(得分:1)

问题已在评论中解决

您正在阻止当前的线程,并且没有给它时间来处理.Tick-Event。 Winforms-Timer不会为它启动一个线程。尝试在genEquation()循环中调用Application.DoEvents()以获取事件。

public class Song {
    private String author, song, url;

    public Song() {}

    public Song(String author, String song, String url) {
        this.author = author;
        this.song = song;
        this.url = url;
    }

    public String getAuthor() { return author; }
    public String getSong() { return song; }
    public String getUrl() { return url; }
}