zoukankan      html  css  js  c++  java
  • System.Threading.Timer

    
    
    using System.Threading;
    using System.Windows.Forms;
    
    /// <summary>
    /// 
    /// Timer(TimerCallback callback, object state, uint duetime, uint period)
    /// duetime:回调首次被调用之前的时间,如果被设置为Timeout.Infinite则会停止计时
    /// period:两次回调之间的时间间隔,如果被设置为Timeout.Infinite则回调只调用一次
    ///
    /// </summary>
    namespace test
    {
        public partial class Form1
        {
            System.Threading.Timer timer;
            int count;
            TextBox textBox1;
    
            //创建计时器和每秒要执行的方法:
            Form1()
            {
                timer = new System.Threading.Timer(st =>
                {
                    ++count;
                    textBox1.AppendText("计数:" + count.ToString() + "
    ");
                    if (count == 100)
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                }, null, Timeout.Infinite, Timeout.Infinite);
    
                // 或(callback是执行函数):
                timer = new System.Threading.Timer(callback, null, 1000, 500); //(毫秒)
            }
    
    
            private void Callback(Object state)
            {
                // 执行操作,执行完归零计时器,回调callback,如此循环
                timer.Change(1000, 500);
            
                //  启动
                textBox1.AppendText("开始
    ");
                count = 0;
                timer.Change(0, 1000);
                
                // 暂停
                timer.Change(Timeout.Infinite, Timeout.Infinite);
                
                // 继续
                timer.Change(0, 1000);
                
                // 停止
                timer.Change(Timeout.Infinite, Timeout.Infinite);
                count = 0;
            }
        }
    }
    
    
    
    class Program
    {
       int TimesCalled = 0;
       void Display(object state)
       {
         Console.WriteLine("{0} {1} keep running.", (string)state, ++TimesCalled);
       }
       static void Main(string[] args)
       {
         Program p = new Program();
         //2秒后第一次调用,每1秒调用一次
         System.Threading.Timer myTimer = new System.Threading.Timer(p.Display, "Processing timer event", 2000, 1000);
         // 第一个参数是:回调方法,表示要定时执行的方法,第二个参数是:回调方法要使用的信息的对象,或者为空引用,第三个参数是:调用 callback 之前延迟的时间量(以毫秒为单位),指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。第四个参数是:定时的时间时隔,以毫秒为单位
    
         Console.WriteLine("Timer started.");
         Console.ReadLine();
       }
    }
    
    
  • 相关阅读:
    HTML5画图板PhoneGap移植
    简易WCF负载均衡方案
    坑爹的“类型初始值设定项引发异常”
    关于for循环中变量定义的位置
    有道云笔记open api sdk for .net α版
    SL/WPF仿WIN8进度条
    HTML5做个画图板
    Google搜索命令“site:”运算符高级使用技巧:
    ubuntu系统托盘不显示ibus输入法图标(语言栏输入法)的解决方法:
    DOS中如何删除文件夹~
  • 原文地址:https://www.cnblogs.com/jshchg/p/12950775.html
Copyright © 2011-2022 走看看