• C# 多线程详解 Part.03 (定时器)


    Timer 类: 
        设置一个定时器,定时执行用户指定的函数。定时器启动后,系统将自动建立一个新的线程,执行用户指定的函数。

    using System;
    using System.Threading;
    namespace ThreadExample
    {
        class TimerExampleState
        {
            public int counter = 0;
            public Timer tmr;
        }
     
        class App
        {
            public static void Main()
            {
                TimerExampleState s = new TimerExampleState();
     
                // 创建代理对象 System.Threading.TimerCallback,该代理将被定时调用 
                TimerCallback timerDelegate = new TimerCallback(CheckStatus);
                
                // 创建一个时间间隔为 1s 的定时器 
                // 第1个参数:指定了 TimerCallback 委托,表示要执行的方法; 
                // 第2个参数:一个包含回调方法要使用的信息的对象,或者为空引用; 
                // 第3个参数:延迟时间--计时开始的时刻距现在的时间,单位是毫秒,指定为"0"表示 立即启动计时器; 
                // 第4个参数:定时器的时间间隔--计时开始后,每隔这么长的一段时间,TimerCallback 所代表的方法将被调用一次 
                Timer timer = new Timer(timerDelegate, s, 1000, 1000);
                s.tmr = timer;
                
                // 主线程停下来等待 Timer 对象的终止 
                while (s.tmr != null)
                {
                    Thread.Sleep(0);
                }
                Console.WriteLine("Timer example done.");
                Console.ReadLine();
            }
     
            /// <summary>
            /// 下面是被定时调用的方法
            /// </summary>
            /// <param name="state"></param> 
            static void CheckStatus(Object state)
            {
                TimerExampleState s = (TimerExampleState)state;
                s.counter++;
                Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);
                if (s.counter == 5)
                {
                    //使用 Change 方法改变了时间间隔为2秒,再等待10秒 
                    (s.tmr).Change(10000, 2000);
                    Console.WriteLine("changed");                
                }
                if (s.counter == 10)
                {
                    Console.WriteLine("disposing of timer!");
                    s.tmr.Dispose();
                    s.tmr = null;
                }
            }
        }
    }

         程序首先创建了一个定时器,它将在创建 1 秒之后开始每隔 1 秒调用一次 CheckStatus() 方法。当调用 5 次以后,CheckStatus() 方法中修改了时间间隔为 2 秒,在并且指定在 10 秒后重新开始。当计数达到 10 次, 调用 Timer.Dispose()方法删除了 timer 对象,主线程于是跳出循环,终止程序。

  • 相关阅读:
    判断一个点是否在一个不规则多边形内算法
    vue-cli 3.0 安装和创建项目流程
    微信小程序分享朋友圈的实现思路与解决办法
    vue2.0中关于active-class
    Nginx服务启动脚本
    Linux系统优化
    URL检测脚本
    Mysql读写分离php脚本
    Memcahed服务异常监控脚本
    一致性哈希算法PHP测试片段
  • 原文地址:https://www.cnblogs.com/zxtceq/p/5667304.html
Copyright © 2020-2023  润新知