Timer in C#
- What is the Timer Class in C#?
- Basic Timer Implementation
- Using Timer with Cancellation
- Advanced Timer Features
- Conclusion
- FAQ

Creating a timer in C# can be a game-changer for developers looking to execute tasks at specific intervals or after a certain delay. The Timer class in C# provides a straightforward way to accomplish this, enabling you to run code periodically or after a specified time. Whether you’re building a simple application or working on a complex project, understanding how to implement a timer can enhance your program’s functionality.
In this article, we’ll explore the Timer class in C#, including its different types and practical examples to help you get started. Let’s dive into the world of timers and see how they can make your coding life easier.
What is the Timer Class in C#?
The Timer class in C# is part of the System.Timers namespace and is designed to execute a method at specified intervals. It can be particularly useful in scenarios where you need to perform repeated tasks without blocking the main thread of your application. There are several types of timers available in C#, including the Timer class, System.Threading.Timer, and System.Windows.Forms.Timer, each serving different purposes based on the context of your application.
The Timer class operates on a thread pool thread, which means it can run concurrently with other operations in your application. This feature is especially beneficial for applications that require high responsiveness. With the Timer class, you can easily set the interval for the timer and specify the method to be executed when the timer elapses.
Basic Timer Implementation
To create a basic timer in C#, you can utilize the Timer class from the System.Timers namespace. Here’s a simple example to illustrate its usage.
using System;
using System.Timers;
class Program
{
private static Timer timer;
static void Main()
{
timer = new Timer(2000);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press [Enter] to exit the program.");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
}
}
Output:
The Elapsed event was raised at 12:00:02.123
The Elapsed event was raised at 12:00:04.123
The Elapsed event was raised at 12:00:06.123
In this code, we create a Timer that triggers every two seconds (2000 milliseconds). The OnTimedEvent
method is executed each time the timer elapses, printing the current time to the console. The AutoReset
property is set to true, allowing the timer to restart automatically after each interval. The program runs until the user presses the Enter key, demonstrating a simple yet effective use of the Timer class.
Using Timer with Cancellation
Sometimes, you may want to stop the timer based on certain conditions. This can be easily achieved by calling the Stop
method on the Timer instance. Here’s an example that incorporates cancellation.
using System;
using System.Timers;
class Program
{
private static Timer timer;
private static int count = 0;
static void Main()
{
timer = new Timer(1000);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press [Enter] to exit the program.");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
count++;
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
if (count == 5)
{
Console.WriteLine("Stopping the timer.");
timer.Stop();
}
}
}
Output:
The Elapsed event was raised at 12:00:01.123
The Elapsed event was raised at 12:00:02.123
The Elapsed event was raised at 12:00:03.123
The Elapsed event was raised at 12:00:04.123
The Elapsed event was raised at 12:00:05.123
Stopping the timer.
In this example, the timer is set to trigger every second. We introduce a counter that increments with each elapsed event. Once the counter reaches five, we stop the timer using the Stop
method, demonstrating how to control the timer’s execution based on specific conditions.
Advanced Timer Features
The Timer class also offers advanced features such as setting the interval dynamically and handling exceptions. Here’s a more complex example that showcases these features.
using System;
using System.Timers;
class Program
{
private static Timer timer;
static void Main()
{
timer = new Timer(1500);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press [Enter] to exit the program.");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
try
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
if (e.SignalTime.Second % 10 == 0)
{
throw new InvalidOperationException("Simulated exception.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
}
}
}
Output:
The Elapsed event was raised at 12:00:01.123
The Elapsed event was raised at 12:00:02.123
The Elapsed event was raised at 12:00:03.123
The Elapsed event was raised at 12:00:04.123
The Elapsed event was raised at 12:00:05.123
The Elapsed event was raised at 12:00:06.123
The Elapsed event was raised at 12:00:07.123
The Elapsed event was raised at 12:00:08.123
The Elapsed event was raised at 12:00:09.123
The Elapsed event was raised at 12:00:10.123
Exception caught: Simulated exception.
In this more advanced example, we simulate an exception every time the elapsed event occurs on the 10th second. We catch this exception to prevent the application from crashing, showcasing how to handle errors gracefully within a timer’s event handler. This capability is crucial for building robust applications that can handle unexpected situations without failing completely.
Conclusion
The Timer class in C# is a versatile tool that can significantly enhance your applications by allowing you to execute tasks at specified intervals. Whether you’re building a simple console application or a complex system, understanding how to implement and control timers can improve your program’s efficiency and responsiveness. From basic implementations to advanced error handling, the Timer class provides the flexibility you need to create dynamic applications. So, the next time you find yourself needing a timer, remember the power of the Timer class in C#.
FAQ
-
What is the Timer class in C#?
The Timer class in C# is used to execute a method at specified intervals, allowing for periodic task execution. -
How do I stop a timer in C#?
You can stop a timer in C# by calling the Stop method on the Timer instance. -
Can I set a timer to run on a specific thread?
Yes, the Timer class in C# operates on a thread pool thread, allowing it to run concurrently with other operations. -
What happens if an exception occurs in the timer’s event handler?
If an exception occurs, it can be caught and handled within the event handler to prevent the application from crashing. -
Is the Timer class suitable for high-precision timing?
For high-precision timing, consider usingSystem.Diagnostics.Stopwatch
or other specialized timing mechanisms, as Timer class precision may vary.
using the Timer class. This comprehensive guide covers basic implementations, cancellation methods, and advanced features, helping you enhance your application’s functionality. Discover practical examples and best practices for using timers effectively in your C# projects.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn