- // @ 来源于挽留刀的技术系列文章-C#的多线程机制探索
- using System;
- using System.Text;
- using System.Threading;
- namespace MutiThread
- {
- /* 定时器实现的多线程,Timer类的作用是设置一个定时器,定时执行用户
- * 指定的函数,而这个函数的传递是靠另外一个代理对象TimerCallback.
- * 定时器启动后,系统将自动建立一个新的线程,并且在这个线程里执行
- * 用户指定的函数 */
- class TimerExampleState
- {
- public int counter = 0;
- public Timer tmr;
- }
- class App
- {
- public static void Main()
- {
- TimerExampleState s = new TimerExampleState();
- // 创建代理对象TimerCallback,该代理将被定时调用
- TimerCallback timerDelegate = new TimerCallback(CheckStatus);
- // 创建一个时间间隔为1s的定时器,延时1s后,每隔1s执行timerDelegate所代表的方法一次
- Timer timer = new Timer(timerDelegate, s, 1000, 1000);
- s.tmr = timer;
- // 当s.tmr不为null是,让主线程停下来等待Timer对象的终止
- while (s.tmr != null)
- Thread.Sleep(0);
- Console.WriteLine("Timer example done.");
- Console.ReadLine();
- }
- // 下面是被定时调用的方法
- static void CheckStatus(Object state)
- {
- TimerExampleState s = (TimerExampleState)state;
- s.counter++;
- Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);
- // 当计数为5时,改变timer的间隔设置
- if (s.counter == 5)
- {
- // 使用Change方法改变了时间间隔
- (s.tmr).Change(10000, 2000);
- Console.WriteLine("changed...");
- }
- // 当计数为10时,删除timer对象
- if (s.counter == 10)
- {
- Console.WriteLine("disposing of timer...");
- s.tmr.Dispose();
- s.tmr = null;
- }
- }
- }
- }
多线程进阶代码四
最新推荐文章于 2023-07-06 13:57:28 发布