Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Examples of single-thread and multi-thread usage of timer timer in .NET Framework

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the examples of single-threaded and multithreaded usage of timer timer in .NET Framework. It is very detailed and has a certain reference value. Interested friends must read it!

If you need to repeat some methods at regular intervals, the easiest way is to use a timer. Compared to the following example, timers can easily and efficiently use memory and resources:

New Thread (delegate () {while (enabled) {DoSomeAction (); Thread.Sleep (TimeSpan.FromHours (24));}}) .Start ()

Not only will this permanently take up a thread, but without extra code, DoSomeAction will happen at a later time every day. The timer solves these problems.

The .NET Framework provides four timers. The following two classes are general multithreaded timers:

(1) System.Threading.Timer

(2) System.Timers.Timer

The other two are dedicated single-thread timers:

(3) System.Windows.Forms.Timer (timer of Windows Forms)

(4) System.Windows.Threading.DispatcherTimer (timer of WPF)

Multithreaded timers are more powerful, precise, and flexible, while single-threaded timers are safe and convenient for simple tasks of updating Windows Forms and WPF controls.

1. Multithreaded timer Permalink

System.Threading.Timer is the simplest multithreaded timer: it has only one construction method and two common methods (to please the minimalist, and the author of this book! ). In the next example, a timer calls the Tick method after 5 seconds to print "tick …" and then prints it every second until the user presses enter:

Using System;using System.Threading;class Program {static void Main () {/ / interval 5000ms for the first time, followed by 1000ms Timer tmr = new Timer (Tick, "tick...", 5000, 1000); Console.ReadLine (); tmr.Dispose (); / / stop timer and perform cleanup work} static void Tick (object data) {/ / here runs Console.WriteLine (data) on a thread pool thread / / print "tick..."}}

You can then change the timer interval by calling the Change method. If you want the timer to be triggered only once, you can specify Timeout.Infinite as the last parameter of the constructor.

The .NET Framework provides another timer class with the same name under the System.Timers namespace. It just encapsulates System.Threading.Timer and provides additional convenience using exactly the same underlying engine. The following is a brief introduction to the added features:

(1) Component is implemented, which is allowed to be used in Visual Studio designers.

(2) the Interval attribute replaces the Change method.

(3) the Elapsed event replaces the callback delegate.

(4) the Enabled attribute is used to start or stop the timer (the default is false).

(5) Start and Stop methods to avoid confusion about the Enabled property.

(6) AutoReset identification to specify whether it is a repeatable event (default is true).

The SynchronizingObject property provides Invoke and BeginInvoke methods that are used to safely invoke methods on WPF and Windows Forms controls.

Here's an example:

The using System;using System.Timers; / / namespace is Timers instead of Threadingclass SystemTimer {static void Main () {Timer tmr = new Timer (); / / No parameter tmr.Interval = 500; tmr.Elapsed + = tmr_Elapsed; / / use events instead of delegated tmr.Start (); / / start timer Console.ReadLine (); tmr.Stop () / / stop timer Console.ReadLine (); tmr.Start (); / / restart timer Console.ReadLine (); tmr.Dispose (); / / permanent stop timer} static void tmr_Elapsed (object sender, EventArgs e) {Console.WriteLine ("Tick");}}

Multithreaded timers use thread pools to allow a small number of threads to serve multiple timers. This means that callback methods or Elapsed events may be triggered on different threads each time. In addition, the Elapsed is always triggered almost on time, regardless of whether the previous Elapsed completes execution or not. Therefore, callback methods or event handlers must be thread-safe.

The accuracy of multithreaded timers depends on the operating system, usually in the 10-20 ms range. If you need higher precision, you can use native interoperability (native interop) to call the Windows multimedia timer, which can increase the precision to 1 ms. It is defined in winmm.dll, which first calls timeBeginPeriod to inform the operating system that you need higher timer precision, and then calls timeSetEvent to start the multimedia timer. When you are done, call timeKillEvent to stop the timer, and finally call timeEndPeriod to inform the operating system that you no longer need higher timer precision. Complete examples can be found online by searching the keyword dllimport winmm.dll timesetevent.

two。 Single thread timer Permalink

The .NET Framework provides two timers designed to eliminate thread safety issues in WPF and Windows Forms applications:

System.Windows.Threading.DispatcherTimer (WPF)

System.Windows.Forms.Timer (Windows Forms)

Single-threaded timers are not designed to work outside their specific environment. For example, if you use a Windows Forms timer in a Windows system service application, the Timer event will not be triggered!

They all expose members like System.Timers.Timer (Interval, Tick, Start, and Stop) and use them similarly. But the difference is how it works internally. Instead of using thread pools to generate timer events, WPF and Windows Forms timers rely on the underlying message loop mechanism (message pumping mechanism) of the UI model. This means that the Tick event is always triggered by the thread that created the timer, and in a normal program, it is the thread that manages all UI elements and controls. This has many benefits:

Single-threaded timers are safer and more convenient for simple tasks such as updating Windows Forms controls or WPF. A SynchronizingObject object that securely invokes methods in WPF or Windows Forms.

Single-threaded timers are timers designed to belong to their execution environment. If you use Windows Forms in a Windows service application, the Timer,timer event will not be triggered, only in the corresponding environment.

Like System.Timers.Timer, they provide the same members (Interval,Tick,Start,Stop), but their internal working principles are different, and the timers of WPF and Windows Forms use the message loop mechanism instead of the thread pool mechanism to generate messages.

You don't have to think about thread safety.

The new Tick is not triggered until the previous Tick finishes execution.

You can update the UI control directly in the code handling the Tick time event without calling Control.Invoke or Dispatcher.Invoke.

This sounds incredible until you realize that programs that use these timers are not really multithreaded and will not be executed in parallel. A thread serves all timers and also handles UI events. This brings the disadvantage of a single-threaded timer:

Unless the Tick event handler executes quickly, the UI loses its response.

This makes WPF and Windows Forms timers available only for small tasks, usually those that update the appearance of UI (for example, display clocks or countdown). Otherwise, you need a multithreaded timer.

In terms of precision, single-threaded timers are similar to multithreaded timers (tens of milliseconds), but are generally less precise because they are delayed by other UI requests (or other timer events).

The single-threaded timer is based on the Windows message loop, and the application processes the timer's messages synchronously. You will find that the UI interface is relatively slow. The solution to this problem is to use multithreaded timers.

The disadvantage of single-threaded timers: unless the code for handling Tick events executes very quickly, the UI interface becomes slow to respond. So the timers of WPF and Windows Forms are very suitable for small tasks, especially for interface updates. Such as clock and count display. Otherwise, you need a multithreaded timer

This is all of the article "examples of single-threaded and multithreaded usage of timer timer in .NET Framework". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report