Timer: Comparison of Timer classes in. NET Framework Class Libraries

Source: Internet
Author: User
Tags net thread

Summary

In client programs and server components (including windows Services), timer (timer) usually plays an important role. Writing efficient managed code driven by timer requires a clear understanding of program processes and. net thread models .. NET Framework Class Library provides three different timer classes: System. Windows. Forms. Timer, System, Timers. Timer and System. Threading. Timer. Each Timer class is designed and optimized for different scenarios. This article studies these three Timer classes to help you understand how and when to use them.

 

Directory

System. Windows. Forms. Timer

System. Timers. Timer

System. Threading. Timer

Thread-safe programming of Timer

Reimport of timer events

Conclusion

 

Microsoft®Windows®The Timer object in allows you to control the behavior. The most common usage of Timer is to regularly start a process, set the interval between events, and maintain consistent animation speed when processing images (regardless of the processor speed ). In the past®For developers, Timer can even be used to simulate multiple tasks.

As you think, Microsoft. NET Framework provides you with the tools needed to process these tasks. 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 Visual Studio®In the. NET toolbox, you can drag them directly to the Windows Form Designer or component designer. If you are not careful, the trouble begins.

The Visual Studio. NET toolkit has a Timer control on both the Windows Forms page and component page (see figure 1 ). It's easy to make mistakes, or even worse, you don't realize they are different. Use the Timer control on the Windows Forms page only when the target is a Windows Forms designer. This control will place an instance of the System. Windows. Forms. Timer class on your form. Just like other controls in the toolbox, you can enable Visual Studio. NET to automatically generate them, or manually instantiate and initialize the class.

 

 


Figure 1 timer control

 

The Timer control on the component page can be safely used for any class. This control creates an instance of the System. Timers. Timer class. If you use the Visual Studio. NET toolbox, you can safely use this Timer either in the Windows Form Designer or in the component designer. When you process a class that inherits from System. ComponentModel. Component (for example, processing Windows Services), Visual Studio. NET uses the Component designer. The System. Threading. Timer class is not in the Visual Studio. NET toolkit. It is a little more complex, but it also provides more advanced control. You will see it later in this article.

 

First, let's take a look at System. Windows. Forms. Timer and System. Timers. Timer. These two classes have very similar object models. Later I will explore more advanced Sytem. Threading. Timer classes. Figure 2 shows the screen of the example program I referenced in this article. This program will help you better understand these classes. You can download the complete code from the link above the article and use it for testing.

 

 


Figure 2 example Program

 

System. Windows. Forms. Timer

If you are looking for a timer, you will find the wrong place. The Timer event triggered by this Timer class is synchronized with other code of your Windows Forms Application. That is to say, the Application code being executed will never be preemptible by the Timer class instance (assuming you didn't call Application. DoEvents ). Like the rest of the code of a typical Windows form application, any code in the Timer event processor of this Timer class is executed using the UI thread of the application. During idle time, the UI thread is also responsible for processing all messages in the Windows message queue of the application, including Windows API messages and Tick events triggered by the Timer class. When the application is not busy with other tasks, the UI thread processes these messages.

If you are in Visual Studio. NET, you have written VB code before. You may know that in Windows-based applications, the only way to allow the UI thread to respond to Windows messages when executing the event processor is to call the Application. doEvents method. As in VB, calling Application. DoEvents in. NET Framework may cause some problems. Application. DoEvents is handed over to the UI message pump, allowing you to process all unprocessed events. This will change the program execution path I just mentioned. If you call Application. DoEvents in your code, your program flow will be interrupted to process the Timer events triggered by the instance of the Timer class. This will lead to unpredictable behavior and make debugging difficult.

When we execute the example program, the behavior of this Timer class is obvious. Click the Start button of the example program, click the Sleep button, and then click the Stop button to generate the following output:

System. Windows. Forms. Timer Started @ 4:09:28

--> Timer Event 1 @ 4:09:29 on Thread: UIThread

--> Timer Event 2 @ 4:09:30 on Thread: UIThread

--> Timer Event 3 @ 4:09:31 on Thread: UIThread

Sleeping for 5000 ms...

--> Timer Event 4 @ 4:09:36 on Thread: UIThread

System. Windows. Forms. Timer Stopped @ 4:09:37

 

The example Program sets the Interval attribute of the System. Windows. Forms. Timer class to 1000 milliseconds. As you can see, if the timer event processor continues to capture the timer event when the main UI thread is sleeping (5 seconds), once the UI thread is awakened again, it should display five timer events-one for every second when the UI thread is sleeping. However, timer is suspended when the UI thread is sleeping.

Programming with System. Windows. Forms. Timer is simple enough-it has a very simple and intuitive programming interface. The Start and Stop methods provide an Enable attribute for Win32®SetTimer/KillTimer function lightweight encapsulation. The Interval attribute mentioned above is self-explanatory. Although technically, you can set the Interval attribute as low as one millisecond, you should know. NET Framework documentation says this property can only be accurate to about 55 milliseconds (assuming the UI thread can be used for processing ).

Capture events triggered by instances of the System. Windows. Forms. Timer class by associating the Tick event to the standard EventHandler proxy, as shown in the code snippet in the following example:

System. Windows. Forms. Timer tmrWindowsFormsTimer = new

System. Windows. Forms. Timer ();

TmrWindowsFormsTimer. Interval = 1000;

TmrWindowsFormsTimer. Tick + = new

EventHandler (tmrWindowsFormsTimer_Tick );

TmrWindowsFormsTimer. Start ();

...

Private void tmrWindowsFormsTimer_Tick (object sender,

System. EventArgs e ){

// Do something on the UI thread...

}

 

System. Timers. Timer

In the. NET Framework documentation, System. Timers. Timer is a server-based Timer designed and optimized for multi-threaded environments. Instances of this Timer class can be securely accessed from multiple threads. Unlike System. windows. forms. timer, System. timers. by default, the Timer class obtains a worker thread from the thread pool in the runtime of the common language to call your timer event processor. This means that the code in your Elapsed event processor must comply with the golden Win32 programming rule: the control instance cannot be accessed by any thread other than the thread that instantiates it.

The System. Timers. Timer class provides a simple way to handle such a dilemma-It exposes a public SynchronizingObject attribute. Setting this attribute to an instance of a Windows form (or a control on a Windows form) ensures that the code in your Elapsed event processor runs in the same thread that SynchronizingObject is instantiated.

If you use the Visual Studio. NET toolbox, Visual Studio. NET automatically sets the SynchronizingObject attribute to the current form. At first, it may seem that using this Timer class with the SynchronizingObject attribute is equivalent to using System. Windows. Forms. Timer. This is true for most features. When the operating System notifies the System. Timers. Timer class that the scheduled time has Elapsed, the Timer uses the SynchronizingObject. BeginInvoke method to execute the Elapsed event proxy on the thread that creates the underlying handle of SynchronizingObject. The event processor will be blocked until the UI thread can process it. However, unlike System. Windows. Forms. Timer, events will eventually be triggered. As you can see in Figure 2, System. Windows. Forms. Timer does not trigger an event when the UI thread cannot process it. System. Timers. Timer will route the event to the queue and wait for the UI thread to process it when it is available.

Figure 3 shows how to use the SynchronizingObject attribute. You can use the example program to analyze this class, select the System. Timers. Timer radio button, and execute this class in the same order as System. Windows. Forms. Timer. In this way, the output shown in Figure 4 is generated.

 

Figure 3 use the SynchronizingObject attribute

System. Timers. Timer tmrTimersTimer = new System. Timers. Timer ();

TmrTimersTimer. Interval = 1000;

TmrTimersTimer. Elapsed + = new

ElapsedEventHandler (tmrTimersTimer_Elapsed );

Tmrtimerstze. SynchronizingObject = this; // Synchronize

// The current form...

TmrTimersTimer. Start ();

......

Private void tmrTimersTimer_Elapsed (object sender,

System. Timers. ElapsedEventArgs e ){

// Do something on the UI thread (same thread the form was

// Created on )...

// If we didnt set SynchronizingObject we wocould be on

// Worker thread...

}

Related Article

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.