如何使用计时器每 x 秒更改一次标签文本

How to change label text every x seconds with a timer

我想每 5000 毫秒更新一次表单中标签的文本,我一直在尝试使用计时器,但它不起作用,我也不知道为什么。这是我使用的代码:

private void Form1_Load(object sender, EventArgs e)
{
    openRequests();

    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 20000;
    aTimer.Enabled = true;
}
private  void  OnTimedEvent(object source, ElapsedEventArgs e)
{
    codeComboBox.Items.Clear();
    try
    {
        connectionDB.Open();
        String query = "";
        query = "SELECT GMKEY0 FROM SAM_FILNAS.EGESM1F0 WHERE GMSTX0 = '0' OR GMSTX0 = 'P' ";
        daMAT = new OleDbDataAdapter(query, connectionDB);
        dsMAT = new System.Data.DataSet();
        daMAT.Fill(dsMAT, "sam_filnas.EGESM1F0 ");
        foreach (System.Data.DataTable t in dsMAT.Tables)
        {
            foreach (System.Data.DataRow r in t.Rows)
            {
                codeComboBox.Items.Add(r["GMKEY0"]);
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show("non riesco a scaricare le richieste di manutenzione aperte");
    }
    label7.Text = "CI SONO " + codeComboBox.Items.Count.ToString() + " RICHIESTE DI MANUTENZIONE";
    connectionDB.Close();
    //updateTimer.Start();
    resertAllTheControls();
}

计时器启动,每 5 秒调用一次 onTimeEvent 方法,但由于某种原因似乎该方法的执行停止在 codeComboBox.Items.Clear();

请向我解释为什么会这样。

不要使用 System.Timers.Timer。请改用 System.Windows.Forms.Timer

Elapsed 在 ThreadPool 线程上执行,这意味着您在尝试更改 UI 上的内容时必须使用 Invoke,因为 UI 有它自己的线程。

System.Windows.Forms.TimerTick 事件发生在 UI 线程上,因此不需要任何特殊代码来处理其事件处理程序中的 UI 元素.

System.Timers.Timer 在内部使用 System.Threading.Timer。 来自 System.Threading.Timer 文档页面的 Remarks 段落:

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads.
It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread.
System.Windows.Forms.Timer is a better choice for use with Windows Forms.