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;
    }

  • 相关阅读:
    Python装饰器理解(新手)
    vue项目随笔
    ajax 请求数据传到后台为空字符
    关于document.body.scrollTop 的谷歌,火狐浏览器兼容问题
    Nginx 反向代理解决浏览器跨域问题
    SpringBoot maven build a new demo
    UI收集
    git
    编译
    网络2
  • 原文地址:https://www.cnblogs.com/teamleader/p/1955410.html
Copyright © 2011-2022 走看看