C # code execution at intervals (multithreading)

Source: Internet
Author: User

Summarize the following three methods to implement c # code execution at intervals:

Method 1: Call the thread execution method to implement an endless loop in the method. Set the Sleep time for each loop;

Method 2: Use the System. Timers. Timer class;

Method 3: Use System. Threading. Timer;

01 using System; 02 using System.Collections; 03 using System.Threading; 04   05 public class Test 06 { 07   08      public static void Main() 09      { 10          Test obj = new Test(); 11          Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString()); 12   13          // Method 1: Call the thread execution method to implement an endless loop in the method, and set the time for each loop Sleep 14          Thread thread = new Thread( new ThreadStart(obj.Method1)); 15          thread.Start(); 16   17   18          // Method 2: Use the System. Timers. Timer class 19          System.Timers.Timer t = new System.Timers.Timer(100); // Instantiate the Timer class and set the time interval 20          t.Elapsed += new System.Timers.ElapsedEventHandler(obj.Method2); // Execute the event at the time of arrival 21          t.AutoReset = true ; // Set whether to execute once (false) or always execute (true) 22          t.Enabled = true ; // Whether to execute the System. Timers. Timer. Elapsed event 23          while ( true ) 24          { 25              Console.WriteLine( "test_" + Thread.CurrentThread.ManagedThreadId.ToString());

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.