views:

10283

answers:

3

Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.

+10  A: 

Use the System.Threading.Timer class.

System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.

There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.

It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object.

Here's an example of a timer in a console application:

using System; 
using System.Threading; 
public static class Program { 

public static void Main() { 

   Console.WriteLine("Main thread: starting a timer"); 
   Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); 
   Console.WriteLine("Main thread: Doing other work here...");
   Thread.Sleep(10000); // Simulating other work (10 seconds)
   t.Dispose(); // Cancel the timer now
}
// This method's signature must match the TimerCallback delega
private static void ComputeBoundOp(Object state) { 
   // This method is executed by a thread pool thread 
   Console.WriteLine("In ComputeBoundOp: state={0}", state); 
   Thread.Sleep(1000); // Simulates other work (1 second)
   // When this method returns, the thread goes back 
   // to the pool and waits for another task 
}

}

From the book CLR Via C# by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.

Ash
Can you supply a little more information on the actual coding?
mm2010
Does the example from msdn work for you?http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
Eric Tuttleman
Eric, I haven't tried it but would not be unusual if there was a problem with it. I notice it is also trying to do some sort of inter-thread synchronisation, this is alsways an area that can be tricky to get right. If you can avoid it in your design, it is always smart to do so.
Ash
Ash - I definitely agree about msdn examples. I wouldn't immediately discount the synchronization code though, if the timmer runs in it's own thread, then you are writing a multi-threaded app and need to be aware of issues relating to synchronization.
Eric Tuttleman
+1  A: 

Here is the code to create a simple one second timer tick:

  using System;
  using System.Threading;

  class TimerExample
  {
      static public void Tick(Object stateInfo)
      {
          Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
      }

      static void Main()
      {
          TimerCallback callback = new TimerCallback(Tick);

          Console.WriteLine("Creating timer: {0}\n", 
                             DateTime.Now.ToString("h:mm:ss"));

          // create a one second timer tick
          Timer stateTimer = new Timer(callback, null, 0, 1000);

          // loop here forever
          for (; ; ) { }
      }
  }

And here is the resulting output:

    c:\temp>timer.exe
    Creating timer: 5:22:40

    Tick: 5:22:40
    Tick: 5:22:41
    Tick: 5:22:42
    Tick: 5:22:43
    Tick: 5:22:44
    Tick: 5:22:45
    Tick: 5:22:46
    Tick: 5:22:47
jussij
+1  A: 

You can also use your own timing mechanisms if you want a little more control, but possibly less accuracy and more code/complexity, but I would still recommend a timer. Use this though if you need to have control over the actual timing thread:

private void ThreadLoop(object callback)
{
    while(true)
    {
     ((Delegate) callback).DynamicInvoke(null);
     Thread.Sleep(5000);
    }
}

would be your timing thread(modify this to stop when reqiuired, and at whatever time interval you want).

and to use/start you can do:

Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop));

t.Start((Action)CallBack);

Callback is your void parameterless method that you want called at each interval. For example:

private void CallBack()
{
    //Do Something.
}
mattlant
If I want to run a batch job until it times out, would your suggestion here be the best one?
mm2010