zoukankan      html  css  js  c++  java
  • 线程中Timer类使用(摘自cnblogs)


    下面这段程序演示了Timer类的用法。

    using System;
    using System.Threading;
    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的定时器
            Timer timer = new Timer(timerDelegate, s, 10001000);
            s.tmr 
    = timer;

            
    //主线程停下来等待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);
            
    if (s.counter == 5)
            
    {
                
    //使用Change方法改变了时间间隔
                (s.tmr).Change(50002000);
                Console.WriteLine(
    "changed");
            }

            
    if(s.counter == 10)
            
    {
                Console.WriteLine(
    "disposing of timer");
                s.tmr.Dispose();
                s.tmr 
    = null;
            }

        }

    }

         程序首先创建了一个定时器,它将在创建1秒之后开始每隔1秒调用一次CheckStatus()方法,当调用5次以后,在CheckStatus()方法中修改了时间间隔为2秒,并且指定在5秒后重新开始。当计数达到10次,调用Timer.Dispose()方法删除了timer对象,主线程于是跳出循环,终止程序。
  • 相关阅读:
    摄影测量技术和立体捕捉
    面向 Unity* 软件和虚拟现实的优化:运行时生成内容
    优化 VR 动作类游戏《Space Pirate Trainer*》以便在英特尔® 集成显卡上实现卓越的表现
    VR电竞游戏在英特尔®架构上的用户体验优化
    《物质世界 (Outward)》证明不必压缩制作大型角色扮演游戏的时间
    采用棋盘渲染在英特尔集成显卡上进行实时升级
    数字绘画:快节奏绘画流程
    实时模型 — 超越多边形计算
    舆情文本分析
    python评分卡
  • 原文地址:https://www.cnblogs.com/xiaobaigang/p/930238.html
Copyright © 2011-2022 走看看