Timers in C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

The Timer class (server-based timer) lets you specify a recurring interval at which the elapsed event is raised. This way we can do regular processing inside the event code block when the timer event occurs. Timers are used to generate recurring events in an application. Some members of the Timer class are described in Table 21.10. 

table21.10.gif

Table 21.10: Timer Class Members 

We use the Timer class to work with worker threads in a multithreaded environment; it is based on server-based timers rather than Windows timers. Server-based timers are more reliable than Windows timers. With server-based timers, we can move among threads to handle the raised elapsed event. Windows timers, on the other hand, were not really intended for switching between threads. The Windows timer is optimized for use in Windows Forms applications and is assumed to be thread-safe. The server-based timer is an updated Windows timer that has been optimized to run in a multithreaded server environment. The Windows timer lives in the System.Windows.Forms namespace, and the server-based timer resides in the System.Timers namespace. Intervals are specified in milliseconds for timers, to trigger events after that time has gone. When the AutoReset field of the Timer class is set to false, the elapsed event is triggered only once by the timer after the first interval has elapsed. If you want to raise the elapsed event each time the time interval occurs in perpetuity, set AutoReset to true. Since both timer usages are almost identical, we choose to demonstrate the server-based timer because of its multithreaded nature. The sample code in Listing 21.25 shows how to use a Timer object that is triggered on 1,000-millisecond intervals. 

Listing 21.25: Using Timers (timer1.cs) 

using System;
using System.Timers;
using System.Threading;

public class Test
{
    public static void Main()
    {
        System.Timers.Timer myTimer = new System.Timers.Timer();
        myTimer.Elapsed += new ElapsedEventHandler(OnTimer);
        myTimer.Interval = 1000;
        myTimer.Enabled = true;
        myTimer.AutoReset = false;

        Console.WriteLine(@"Press 'q' and 'Enter' to quit...");

        while (Console.Read() != 'q')
        {
            Thread.Sleep(1000);
        }
    }

    public static void OnTimer(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("DateTime: " + DateTime.Now);
        System.Timers.Timer theTimer = (System.Timers.Timer)source;
        theTimer.Interval += 1000;
        theTimer.Enabled = true;
    }
}



Figure 21.1: Timer Output from One-Second 

Notice the time difference between each time trigger. This shows that the server-based timers are not pulsing as we expected, because although we enabled our timer to trigger every one second, the event handler was delayed in order to handle other activity of the CPU. Server-based timers are dependent on the operating system's multithreading character on which our code runs, and the program must obey the CPU priority rules when using these timers. 

Conclusion

Hope this article would have helped you in understanding Timers in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg

The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all