Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my System.Timers.Timer event not firing in C#

Tags:

c#

timer

System.Timers.Timer timer = new System.Timers.Timer();

private void button1_Click(object sender, EventArgs e)
{
    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    timer.Interval = 2000;

    timer.Enabled = true;
    timer.Start();
}

private void timer_Elapsed(object myobject, System.Timers.ElapsedEventArgs e)
{
    Say("Time hit" + DateTime.Now.ToString());
}

what am i missing?

EDIT:

Tried to add:

timer.AutoReset = true;

For those curious Say Method is:

private void Say(string s)
        {

            try
            {
                txtSay.AppendText(s + "\r\n");
            }
            catch
            {
            }
        }

The say method doesn't have a problem in there. Works with everything else.

like image 888
Isaac Pounder Avatar asked Dec 28 '22 08:12

Isaac Pounder


2 Answers

I think you didint mentioned that you getting cross thread exception.. try to change code like that:

Invoke(new Action(()=>Say("Time hit" + DateTime.Now.ToString())));
like image 99
Renatas M. Avatar answered Dec 29 '22 22:12

Renatas M.


Because

  1. your Timers.Timer does not set a SyncObject
  2. Therefore your event fires on another thread
  3. Setting the Text property raises a cross-threading Exception
  4. And then you swallow that exception without any trace

    private void Say(string s)
    {
        try
        {
            txtSay.AppendText(s + "\r\n");
        }
        catch  // empty catch-block: the real fundamental problem
        {
        }
    }
    

So the Timer event does fire but it produces an error that remains hidden.

The short, practical solution would be to use a Windows.Timer for a GUI related timer.

like image 34
Henk Holterman Avatar answered Dec 29 '22 22:12

Henk Holterman