C # Console Thread Timer code example

Source: Internet
Author: User

There are three types of timers available in C #:
1. Windows-based standard timer (System.Windows.Forms.Timer)
2. Server-Based Timers (System.Timers.Timer)
3. Thread Timer (System.Threading.Timer)
One, Windows-based standard timer (System.Windows.Forms.Timer)
First, note that the Windows timer is designed for single-threaded environments
This timer is present in the product from the Visual Basic version 1.0 and is basically unchanged
This timer is the simplest one, just drag the Timer control from the Toolbox onto the form, then set the event and interval time properties.
second, server-based Timers (System.Timers.Timer)
System.Timers.Timer does not rely on forms, is a wake-up thread from the thread pool, is an updated version of the classic timer in order to run on a server environment, no ready-made controls are available in the VS2008 Toolbox, and manual encoding is required to use this timer
Three, Thread Timers (System.Threading.Timer)
The thread timer is also not dependent on the form, and is a simple, lightweight timer that uses callback methods instead of using events and is supported by thread pool threads. Thread timers are very useful in scenarios where messages are not sent on threads.

The code example is given only for the use of the console thread timer, followed by several other code examples:

Using system;using system.collections.generic;using system.runtime.interopservices;using System.Text;using system.threading;/************************************************************************//* CSharp Console Thread Timer code example * Powered by:testcs_dn * blog:http://blog.csdn.net/testcs_dn *//********************************* /namespace CSharp Console Thread Timer code example {//<summary>///console Thread Timer code example//Here Demonstrates the application of the Windows API SetConsoleCtrlHandler function, while showing the use of thread timers;///AUTHOR:TESTCS_DN///date:2015-01-03//</summar Y> class Program {///<summary>//////Timer callback function, where to handle the judgment of whether the time is reached and what to do;///</summary        >//<param name= "obj" ></param> public static void Workovertimetimercallback (Object obj)            {DateTime dt = DateTime.Now; if (dt. Hour = = && dt.            Minute > 0) {Console.WriteLine ("OK");   }}//Timer variable     public static System.Threading.Timer Workovertimetimer = null;        Defines the handler delegate delegate bool Consolectrldelegate (int dwctrltype);        const int ctrl_close_event = 2; Import Setctrlhandlerhandler API [DllImport ("Kernel32.dll")] private static extern bool SetConsoleCtrlHandler (C        Onsolectrldelegate Handlerroutine, bool Add); static void Main (string[] args) {consolectrldelegate newdelegate = new Consolectrldelegate (Handlerrouti            NE); if (SetConsoleCtrlHandler (NewDelegate, True)) {//Initialize timer Workovertimetimer = new                System.Threading.Timer (New TimerCallback (workovertimetimercallback), NULL, 1000, 10000); To perform your own task here, I gave an example of "...", in order to show the long task, I used a dead loop;//Avoid too much output, use sleep;//Note: Sleep time is not too long, otherwise it may affect cons Ole.                    ReadKey (), resulting in the inability to receive user input; while (true) {Console.WriteLine ("..."); Thread.Sleep (100); }} else {Console.WriteLine ("Sorry, API injection failed, press any key to exit!")                ");            Console.readkey ();  }}////<summary>///handler routines, where you write handler code for the specified event////</summary>//<param Name= "Ctrltype" ></param>///<returns></returns> static bool Handlerroutine (int ctrlty                    PE) {switch (ctrltype) {case ctrl_close_event://user is shutting down console                    Console.WriteLine (); Console.WriteLine ("The task is not completed, confirm that you want to exit?")                    (y/n) ");                    Consolekeyinfo ki = Console.readkey (); Return KI.                Key = = Consolekey.y;            Default:return true; }        }    }}


C # Console Thread Timer code example

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.