System.Timers.Timer and System.Threading.Timer in C#
The .NET framework provides several classes for implementing timed events within applications. Two commonly used classes are System.Timers.Timer
and System.Threading.Timer
, each suited to different scenarios.
System.Timers.Timer
This class is designed for applications requiring timer events to be raised on a specific thread, typically the UI thread. It offers a simpler interface, primarily suitable for applications needing straightforward timer functionality.
Key Properties and Methods
Interval
: Specifies the time interval (in milliseconds) between timer events.Elapsed
: An event that is raised when the timer's interval elapses. This event handler executes on the thread that created the timer instance.Enabled
: A boolean property controlling whether the timer is running. Setting totrue
starts the timer; setting tofalse
stops it.Start()
: Begins the timer.Stop()
: Stops the timer.
Example Usage (Illustrative):
using System; using System.Timers; public class TimerExample { public static void Main(string[] args) { Timer timer = new Timer(1000); // 1-second interval timer.Elapsed += OnTimedEvent; timer.Enabled = true; Console.ReadKey(); } private static void OnTimedEvent(Object source, ElapsedEventArgs e) { Console.WriteLine("Elapsed!"); } }
System.Threading.Timer
This class provides more fine-grained control over timer operation, including specifying a callback method and state information. It's more versatile but requires a more thorough understanding of threading.
Key Methods
Timer(TimerCallback callback, object state, int dueTime, int period)
: Constructor taking a callback method, state object, initial delay (dueTime
), and period (period
in milliseconds).Change(int dueTime, int period)
: Modifies the timer's delay and period after creation.Dispose()
: Releases resources held by the timer.
Example Usage (Illustrative):
using System; using System.Threading; public class TimerExample { public static void Main(string[] args) { Timer timer = new Timer(OnTimedEvent, null, 0, 1000); // Starts immediately, 1-second interval. Console.ReadKey(); timer.Dispose(); } private static void OnTimedEvent(object state) { Console.WriteLine("Elapsed!"); } }
Choosing the Right Timer
Select System.Timers.Timer
for simpler scenarios where thread affinity is desired. Choose System.Threading.Timer
for more complex requirements or when precise control over timing and thread management is necessary.
Considerations for Console Applications
Ensure the console application does not exit prematurely before the timer completes its operation. Techniques like using Console.ReadKey()
or other blocking mechanisms can prevent immediate termination.