C # Use Timer class for timer tasks

Source: Internet
Author: User
Tags net thread

In C #, there are three Timer classes:

1.system.windows.forms.timer
2.system.threading.timer
3.system.timers.timer

System.Windows.Forms.Timer
is applied to WinForm, it is implemented through the Windows messaging mechanism, similar to the Timer control in VB or Delphi, the internal use of API SetTimer implementation. Its main disadvantage is that the timing is imprecise and that there must be a message loop that the console application (console application) cannot use.

System.Timers.Timer and System.Threading.Timer are very similar, they are implemented through the. NET Thread Pool, lightweight, timed accurately, for applications, There are no special requests for messages. System.Timers.Timer can also be applied to WinForm to completely replace the timer control above. Their disadvantage is that they do not support direct drag-and-drop and require manual coding.

Example:
Using the System.Timers.Timer class

private void Button2_Click (object sender, EventArgs e)
{
	System.Timers.Timer t = new  System.Timers.Timer ( 10000)//Instantiate timer class, set interval time is 10000 milliseconds; 
	t.elapsed + + new  System.Timers.ElapsedEventHandler (theout); Executes the event when the time is reached; 
	T.autoreset =  true;//Whether the setting is executed once (false) or always (true); 
	t.enabled =  true;// Whether to execute the System.Timers.Timer.Elapsed event;
}

private void Ontimedevent (object source, Elapsedeventargs e)
{
	MessageBox.Show ("OK.");
}



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.