Search code examples
c#.netwinformstimercontrols

How to change label text every x seconds with a timer


I want to update the Text of a label in my form every 5000 ms, I've been trying to use a timer, but it doesn't work and I don't know why. This is the code I am using:

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();
}

The timer starts and every 5 seconds the onTimeEvent method is called, but for some reason it seems that the execution of the method stops at codeComboBox.Items.Clear();

Please, explain to me why this happens.


Solution

  • Don't use System.Timers.Timer. Use System.Windows.Forms.Timer instead.

    The Elapsed executes on a ThreadPool thread, meaning you will have to use Invoke when attempting to change things on the UI, because the UI has it own thread.

    System.Windows.Forms.Timer's Tick event occurs on the UI thread, so there is no need for any special code to work with UI elements in it's event handler.

    The System.Timers.Timer use System.Threading.Timer internally. From the Remarks paragraph of the System.Threading.Timer documentation page:

    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.