-
Timer
I have to following code:
PHP Code:
System.Windows.Forms.Timer onCheckTimer = new System.Windows.Forms.Timer();
onCheckTimer.Tick += new EventHandler(checkOnTimer);
Console.WriteLine("Startin TImer...");
onCheckTimer.Interval = 1000;
onCheckTimer.Start();
PHP Code:
static void checkOnTimer(Object myObject, EventArgs myEventArgs)
{
Console.WriteLine(DateTime.Now.ToString());
}
My question is does anyone know why the timer event never gets raised. I took it from the msdn documentation but can't seem to get it work work. The first part of the code is from a console app called and the function would be main.
If anyone has any insight then I would be exteremly greatfull.
Jeremy
-
not sure why that doesn't work, probably needs a container(like a form) or something. This works though, just catch the Elapsed event handler:
PHP Code:
using System;
using System.Timers;
namespace TimeTest
{
public class MainApp
{
public static void Main(string[] args)
{
Timer tmr = new Timer(1000);
tmr.Elapsed += new ElapsedEventHandler(TimeElapsed);
tmr.Start();
Console.ReadLine();
}
public static void TimeElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(e.SignalTime.ToString());
}
}
}
-
Thanks.
Not sure why the first code example did not work, you would think that they would make sure the code out of the documentation would do what is was supposed to.
Jeremy
-
You were using a windows form control. You need to use the generic timer class if you are doing a console app. I don't know why one is different than the other, but there is something there that won't allow it to work.
-
True, however I did find that example in the MSDN documentation describing how to add a timer to a console app.
Jeremy
-
i think the delegate doesnt match up:
PHP Code:
static void checkOnTimer(Object myObject, EventArgs myEventArgs)
{
Console.WriteLine(DateTime.Now.ToString());
}
try using
PHP Code:
public static void TimeElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(e.SignalTime.ToString());
}
-
Watch out, by using the System.Timers.Timer object the elapsed event is in a different thread than the main app. Caught me when I was trying to manipulate a form from within the event.
-
Actually I prefer to have it in a different thread anyways becaues all that it is doing is starting a thread.
Jeremy