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

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 the curious Say method:

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

There are no problems with the say method. Works with everything else.

+4
source share
6 answers

I think you didint mentioned that you get cross-thread exception. try changing the code as follows:

 Invoke(new Action(()=>Say("Time hit" + DateTime.Now.ToString()))); 
+5
source

Because the

  • your Timers.Timer does not set SyncObject
  • Therefore, your event fires in another thread
  • Setting the Text property causes a cross-thread exception
  • And then you swallow this 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 fires, but it causes a hidden error.

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

+5
source

This may not be correct, but following the MSDN example, you do not need to call t.Start (), t.Enable, should start it. Since you start it by executing t.Enabled and t.Start, there may be some conflict with the AutoRest property.

I also have to make sure that the Say method works as it should by adding a breakpoint or something like that. I do not know what you call AppendText in this case.

Guess the job a bit.

0
source

You do not need to install EventHandler in the Click method. Install it, for example. in the constructor of your class, and it will work.

Leave the Start () method in the click function:

 private void button1_Click(object sender, EventArgs e) { timer.Start(); } 
0
source

As Renuse says, you are likely to get an exception because you are trying to update the user interface from another thread. The Timer class runs in a separate thread so as not to interfere with the response of your application.

This is a great example of why try { /* something */ } catch {} is a bad idea - you completely hid the error from yourself by writing this. If you hadn’t written this, you could probably figure out that you need to invoke the user interface update in the correct thread from the exception message.

0
source

In C ++ / CLI (managed by C ++ using .NET - it is really closed to C #) you must set the object to synchronize on this timer.

It might look like this: + -

 timer->SynchronizingObject = txtSay; 

in C # it is possible: with "." instead of "->"

See artice

0
source

Source: https://habr.com/ru/post/1390605/


All Articles