多线程进阶代码四

  1. // @ 来源于挽留刀的技术系列文章-C#的多线程机制探索
  2. using System;
  3. using System.Text;
  4. using System.Threading;
  5. namespace MutiThread
  6. {
  7.     /* 定时器实现的多线程,Timer类的作用是设置一个定时器,定时执行用户
  8.      * 指定的函数,而这个函数的传递是靠另外一个代理对象TimerCallback.
  9.      * 定时器启动后,系统将自动建立一个新的线程,并且在这个线程里执行
  10.      * 用户指定的函数  */
  11.     class TimerExampleState
  12.     {
  13.         public int counter = 0;
  14.         public Timer tmr;
  15.     }
  16.     class App
  17.     {
  18.         public static void Main()
  19.         {
  20.             TimerExampleState s = new TimerExampleState();
  21.             // 创建代理对象TimerCallback,该代理将被定时调用
  22.             TimerCallback timerDelegate = new TimerCallback(CheckStatus);
  23.             // 创建一个时间间隔为1s的定时器,延时1s后,每隔1s执行timerDelegate所代表的方法一次
  24.             Timer timer = new Timer(timerDelegate, s, 1000, 1000);
  25.             s.tmr = timer;
  26.             // 当s.tmr不为null是,让主线程停下来等待Timer对象的终止
  27.             while (s.tmr != null)
  28.                 Thread.Sleep(0);
  29.             Console.WriteLine("Timer example done.");
  30.             Console.ReadLine();
  31.         }
  32.         // 下面是被定时调用的方法
  33.         static void CheckStatus(Object state)
  34.         {
  35.             TimerExampleState s = (TimerExampleState)state;
  36.             s.counter++;
  37.             Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);
  38.             // 当计数为5时,改变timer的间隔设置
  39.             if (s.counter == 5)
  40.             {
  41.                 // 使用Change方法改变了时间间隔
  42.                 (s.tmr).Change(10000, 2000);
  43.                 Console.WriteLine("changed...");
  44.             }
  45.             // 当计数为10时,删除timer对象
  46.             if (s.counter == 10)
  47.             {
  48.                 Console.WriteLine("disposing of timer...");
  49.                 s.tmr.Dispose();
  50.                 s.tmr = null;
  51.             }
  52.         }
  53.     }
  54. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值