PDA

Click to See Complete Forum and Search --> : Timer


Jeremy Martin
Dec 22nd, 2002, 03:19 PM
I have to following 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();



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

pvb
Dec 22nd, 2002, 06:15 PM
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:

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

Jeremy Martin
Dec 22nd, 2002, 06:48 PM
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

hellswraith
Dec 22nd, 2002, 08:24 PM
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.

Jeremy Martin
Dec 22nd, 2002, 11:44 PM
True, however I did find that example in the MSDN documentation describing how to add a timer to a console app.

Jeremy

PT Exorcist
Dec 25th, 2002, 06:56 PM
i think the delegate doesnt match up:

static void checkOnTimer(Object myObject, EventArgs myEventArgs)
{
Console.WriteLine(DateTime.Now.ToString());
}

try using


public static void TimeElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(e.SignalTime.ToString());
}

CornedBee
Dec 27th, 2002, 05:05 AM
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.

Jeremy Martin
Dec 27th, 2002, 08:51 AM
Actually I prefer to have it in a different thread anyways becaues all that it is doing is starting a thread.

Jeremy