实现c#每隔一段时间执行代码

来源:互联网 发布:java web前端框架 编辑:程序博客网 时间:2024/06/05 14:57

方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间; 方法二:使用System.Timers.Timer类; 方法三:使用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 //方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间 14 Thread thread = new Thread(new ThreadStart(obj.Method1)); 15 thread.Start(); 16 17 18 //方法二:使用System.Timers.Timer类 19 System.Timers.Timer t = new System.Timers.Timer(100);//实例化Timer类,设置时间间隔 20 t.Elapsed += new System.Timers.ElapsedEventHandler(obj.Method2);//到达时间的时候执行事件 21 t.AutoReset = true;//设置是执行一次(false)还是一直执行(true) 22 t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件 23 while (true) 24 { 25 Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString()); 26 Thread.Sleep(100); 27 } 28 29 30 //方法三:使用System.Threading.Timer 31 //Timer构造函数参数说明: 32 //Callback:一个 TimerCallback 委托,表示要执行的方法。 33 //State:一个包含回调方法要使用的信息的对象,或者为空引用(Visual Basic 中为 Nothing)。 34 //dueTime:调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。 35 //Period:调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。 36 System.Threading.Timer threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(obj.Method3), null, 0, 100); 37 while (true) 38 { 39 Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString()); 40 Thread.Sleep(100); 41 } 42 43 Console.ReadLine(); 44 }