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

    这个Timer比较原始
    Timer t = new Timer(delegate(object o) {Console.WriteLine("...");}, null, 10000, 1000);
    4个参数
    1. TimerCallback
    2. Object类型的state对象
    3. 等待多久开始执行,如果设置为0则马上执行
    4. 每次执行的时间间隔
     
    这个Timer的回调函数在线程池中执行
     
    没有静态方法,就两个实例方法Change和Dispose.
    没法设置Start, Stop....很不方便,new 完之后直接开始干活。
     
    MSDN:
    As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.
     
    推荐用System.Timers.Timer,这个要方便得多
     
    下面是一个简单的样例:
    class Program
    {
        static void Main(string[] args)
        {
            MyState state = new MyState();
            Timer x = null;
            x = new Timer(delegate(object o) 
            {
                if (state.Counter == 3)//只运行3次
                {
                    Console.WriteLine("3 times only!");
                    x.Dispose();
                    return;
                }
                MyState s = o as MyState;
                s.Counter++;

                Console.WriteLine("do");
            }, state, 2000, 1000);


            Console.ReadKey();
        }
    }

    class MyState
    {
        public int Counter;
    }

  • 相关阅读:
    398. Random Pick Index
    382. Linked List Random Node
    645. Set Mismatch
    174. Dungeon Game
    264. Ugly Number II
    115. Distinct Subsequences
    372. Super Pow
    LeetCode 242 有效的字母异位词
    LeetCode 78 子集
    LeetCode 404 左叶子之和
  • 原文地址:https://www.cnblogs.com/teamleader/p/1955410.html
Copyright © 2011-2022 走看看