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

How to use four kinds of timer Timer in C #

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of how to use the four kinds of C # timer Timer, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to use the four kinds of C # timer Timer. Let's take a look.

1. System.Threading.Timer thread timer

1. The lowest level, lightweight timer. Implemented based on thread pool and working in worker threads.

2. It is not inherently thread-safe and is more troublesome to use than other timers. This timer is generally not suitable for Windows forms environments.

Constructor: public Timer (TimerCallback callback, object state, int dueTime, int period)

The string state= "."; / / state parameter can be passed in the object you want to handle in the callback delegate. You can pass an AutoRestEvent that sends a signal to the main function in the callback function. Timer timer=new Timer (TimeMethod,state,100,1000) / / 100 indicates how long it will start, and 1000 indicates how often it will be executed. Void TimerMethod (object state) {Console.Write (state.ToString ());} timer.Dispose (); / / cancel timer execution 2, System.Timers.Timer server timer

1. The service program for the server, based on System.Threading.Timer, is designed and optimized to be used in multithreaded environment. In this case, you should make sure that the event handler does not interact with UI. System.Timers.Timer is generally used in asp.net.

2. Inherited from Compnent, it exposes the SynchronizingObject attribute, which avoids the problem that components in the main thread cannot be accessed in the thread pool (simulated System.Windows.Forms.Timer single-thread mode). But unless you need more precise control over the timing of events, you should use System.Windows.Forms.Timer instead.

3. The AutoReset property sets whether the timer is re-timed after the Elapsed event is raised. The default is true. If the property is set to False, the timer_Elapsed method is executed only once.

4. System.Timers.Timer is a multithreaded timer. If a Timer is not processed, the new Timer will also be started when it reaches the next point in time. Therefore, Timer is more suitable for performing small tasks that are not too time-consuming. If you run a time-consuming task in Timer, it is easy to cause multi-thread reentry problems caused by timeouts, that is, multiple threads enter the timer_Elapsed method at the same time.

System.Timers.Timer timer = new System.Timers.Timer (); timer.Interval = 500 timer.SynchronizingObject = this;timer.Elapsed+=new System.Timers.ElapsedEventHandler (timer_Elapsed); timer.Start (); private void timer_Elapsed (Object source, Timers.ElapsedEventArgs e) {this.tbTimer.Text = value;}

5. In order to deal with the problem of multithreaded reentry. Locks can be added or flag bits can be added. Interlocked.Exchange provides a lightweight thread-safe way to assign values to objects, so use Interlocked.Exchange to assign values to variables.

Int inTimer = 0; void timer_Elapsed (object sender, System.Timers.ElapsedEventArgs e) {if (Interlocked.Exchange (ref inTimer, 1) = = 0) {Thread.Sleep (3000); string currentThreadId = Thread.CurrentThread.ManagedThreadId.ToString () This.Dispatcher.BeginInvoke (new Action () = > {this.Label_Result.Content + = currentThreadId + ",";}), null); Interlocked.Exchange (ref inTimer, 0);}} 3, System.Windows.Forms.Timer Windows timer

This timer, which inherits directly from Component, is specifically optimized for use with Windows forms and must be used in windows.

Windows timers are built to run on message-based UI threads with precision limited to 5ms. The events executed in the Tick event are the same thread (single-threaded) as the main form and are safe for interaction with UI.

There are only two properties, Enable and Internal, and a Tick event, and you can use the Start () and Stop () methods to control the Enable property.

Using System.Windows.Forms;public Form1 () {InitializeComponent (); this.Load + = delegate {Timer timer = new Timer (); timer.Interval = 500; timer.Tick + = delegate {System.Diagnostics.Debug.WriteLine ($"Timer Thread: {System.Threading.Thread.CurrentThread.ManagedThreadId}") System.Diagnostics.Debug.WriteLine ($"IsThreadPool: {System.Threading.Thread.CurrentThread.IsThreadPoolThread}"); this.lblTimer.Text = DateTime.Now.ToLongTimeString ();}; timer.Start (); System.Diagnostics.Debug.WriteLine ($"Main Thread: {System.Threading.Thread.CurrentThread.ManagedThreadId}");};} 4. System.Windows.Threading.DispatcherTimer

Mainly used in WPF. Properties and methods are similar to System.Windows.Forms.Timer. Tick events in DispatcherTimer are executed in the main thread.

One thing to pay attention to when using DispatcherTimer, because the Tick events of DispatcherTimer are queued in Dispatcher, when the system is under high load, there is no guarantee that it will be executed during the Interval period, and there may be a slight delay, but it is absolutely guaranteed that the execution of Tick will not be earlier than the time set by Interval. If the execution time of Tick is accurate, you can set the priority of DispatcherTimer.

This is the end of the article on "how to use the four kinds of timer Timer in C #". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use the four kinds of C# timer Timer". If you want to learn more knowledge, you are 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