views:

6898

answers:

6

I want to use a timer in my simple .Net application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console app.

Is there a C# Timer (or Timer like) class for use in Console apps?

+16  A: 

System.Timers.Timer

And as MagicKat says:

System.Threading.Timer

You can see the differences here: http://mark.michaelis.net/Blog/SystemWindowsFormsTimerVsSystemThreadingTimerVsSystemTimersTimer.aspx

And you can see MSDN examples here:

http://msdn.microsoft.com/es-es/library/system.timers.timer(VS.80).aspx

And here:

http://msdn.microsoft.com/es-es/library/system.threading.timer(VS.80).aspx

AlbertEin
System.Threading.Timer is another one as well
MagicKat
This does answer the question, but talk about "minimal". Spoon's answer is much better.
OJ
+6  A: 

I would recommend the Timer class in the System.Timers namespace. Also of interest, the Timer class in the System.Threading namespace.

using System;
using System.Timers;

public class Timer1
{
    private static Timer aTimer = new System.Timers.Timer(10000);

    public static void Main()
    {
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

Example from MSDN docs.

spoon16
A: 

System.Diagnostics.Stopwatch if your goal is to time how long something takes to run

DaveK
This is not a timer, this allows you to measure execution of a specific block of code but does not act the same as a timer.
spoon16
A: 

you 've done a great job

mehvish
+1  A: 

It is recommended to not to use System.Timer's Timer class.

Sucharit
+1  A: 

There are at least the System.Timers.Timer and System.Threading.Timer classes that I'm aware of.

One thing to watch out though (if you haven't done this before already), say if you already have the System.Threading namespace in your using clause already but you actually want to use the timer in System.Timers you need to do this:

using System.Threading;
using Timer = System.Timers.Timer;

Jon Skeet has an article just on Timers in his multithreading guide, it's well worth a read: http://www.yoda.arachsys.com/csharp/threads/timers.shtml

theburningmonk