. The use skill of timer class in NET Framework class library

Source: Internet
Author: User
Tags message queue sleep thread visual studio

Timers typically play an important role, whether in client applications or server components, including window services. Writing an efficient timer-driven manageable code requires a clear understanding and mastery of the program flow. The subtlety of the net threading model. NET Framework class library provides three different timer classes: System.Windows.Forms.Timer, System.Timers.Timer, and System.Threading.Timer. Each class is designed and optimized for different occasions. This article will look at these three classes and give you an idea of how and when you should use the class.

The timer object in the microsoft®windows® allows you to control when the behavior occurs. Some of the most common places for timers are regular time to start a process, set intervals between events, and maintain a fixed animation speed when working on graphics (regardless of the speed of the processing function). In the past, timers were even used to simulate multitasking for developers using visual basic®.

As you would expect, Microsoft has equipped you with a number of tools for the different situations you need to deal with. There are three different timer classes in the. NET Framework Class Library: System.windows.forms.timer,system.timers.timer, and System.Threading.Timer. The first two classes appear in the visual studio®. NET Toolbox window, both of which allow you to drag them directly onto the Windows Forms Designer or Component Class Designer. If you are not careful, this is the beginning of trouble.

Visual Studio. The Windows Forms page and component pages on the Net toolbox (see Figure 1) have timer controls. It is very easy to use one of them incorrectly, or worse, to be unaware of their differences. Use the Timer control on Windows Forms pages only when the target is the Windows Forms Designer. This control will place an instance of the Systems.Windows.Forms.Timer class on your form. Like other controls on the toolbox, you can have visual Studio. NET handles its generation or your own manual instances and initializes this class.

Figure 1 Timer Control

The timer control on the component page can be safely used in any class. This control creates an instance of the System.Timers.Timer class. If you are using visual Studio. NET toolbox, either the Windows Forms Designer or the Component Class Designer, you can safely use this class. In Visual Studio. NET, you use the Component Class Designer when you design a class that derives from System.ComponentModel.Component. The System.Threading.Timer class does not appear in visual Studio. NET Toolbox window. It's a little bit more complicated but provides a higher level of control, which you'll see later in this article.

Figure 2 Example Program

Let's first study the System.Windows.Forms.Timer and System.Timers.Timer classes. These two classes have very similar object models. Later I'll explore the more advanced System.Threading.Timer classes. Figure 2 is a screenshot of the example program that I will refer to throughout the article. This application will give you a clear understanding of these timer classes. You can download the complete code from the start link in this article and experiment with it.

System.Windows.Forms.Timer

If you're looking for a metronome, you're already in the wrong place. This timer class raises timer events that are synchronized with the rest of your window application's code. This means that the code being executed is never preempted by instances of this timer class (assuming you do not call application.doevents). Like any other code in a typical form program, any code residing in a timer event handler (referring to the timer class of that type) is also performed using the application's UI thread. At idle time, the UI thread is also responsible for all messages in the form message queue for the application. This includes not only messages raised by this timer class, but also form API messages. The UI thread handles these messages whenever your program is not busy doing anything else.

In Visual Studio. NET if you have written Visual Basic code before, you may know that the only way to get your UI thread to respond to other forms messages in a window application is to invoke the Application.doevents method when you are executing an event handler. As with Visual Basic, invoking application.doevents from the. NET Framework can create many problems. Application.doevents generates control over the UI message pump, allowing you to handle all unhandled events. This can change the desired execution path that I just mentioned. If you have a application.doevents call in your code to handle the timer event generated by the timer class, your program flow may be interrupted. This creates the desired behavior and makes debugging difficult.

Running the example program will make the behavior of this timer class clear. Clicking the Start button of the program, clicking the Sleep button, and then clicking the Stop button will produce the following output:

System.Windows.Forms.Timer Started @ 4:09:28 PM--> Timer Event 1 @ 4:09:29 PM on Thread:UIThread--> Timer EVENT 2 @ 4:09:30 PM on Thread: UIThread--> Timer Event 3 @ 4:09:31 PM on Thread: UIThreadSleeping for 5000 ms...--> Timer Event 4 @ 4:09:36 PM on Thread: UIThreadSystem.Windows.Forms.Timer Stopped @ 4:09:37 PM

Example program sets the Interval property of the System.Windows.Forms.Timer class to 1000 milliseconds. As you can see, when the UI thread is sleeping (5 seconds), if the timer event handler continues to capture the timer event, 5 timer events should be displayed when the sleep thread is awakened again-one per second when the UI thread sleeps. However, when the UI thread is asleep, the timer remains suspended.

The programming of System.Windows.Forms.Timer can be no simpler-it has a very simple and direct programming interface. The start and stop methods actually provide a way to set the enabling properties (which itself is a wrapper over the SetTimer and KillTimer functions of the win32®). The interval attribute I just mentioned, the name itself explains the problem. Even if technically you can set the interval attribute to be as low as 1 milliseconds, but you should know in. NET Framework document indicates that this property is approximately accurate to 55 milliseconds (assuming that the UI thread is available for processing).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.