.net几种timer区别

概述:.net框架不同名称控件都包含了各种timer,但每个timer有什么具体区别呢?

一、System.Threading

        private static void ThreadingTimer()
        {
            Console.WriteLine("System.Threading.Timer call thread id {0}",Thread.CurrentThread.ManagedThreadId);
            using (var t1 = new System.Threading.Timer(
               TimeAction, null, TimeSpan.FromSeconds(2),
               TimeSpan.FromSeconds(3)))
            {

                Thread.Sleep(15000);
            }
        }

        static void TimeAction(object o)
        {
            Console.WriteLine("System.Threading.Timer {0:T}", DateTime.Now);
            Console.WriteLine("System.Threading.Timer callback thread id{0}", Thread.CurrentThread.ManagedThreadId);
        }

运行结果如下

从运行结果可以看出

回调函数执行的线程(callback thread)和调用线程(calling thread)并不是一样的。

二、System.Timers

        private static void TimersTimer()
        {
            Console.WriteLine("System.Timers.Timer call thread id {0}", Thread.CurrentThread.ManagedThreadId);
            var t1 = new System.Timers.Timer(1000);
            t1.AutoReset = true;
            t1.Elapsed += TimeAction;
            t1.Start();
            Thread.Sleep(10000);
            t1.Stop();

            t1.Dispose();
        }

        static void TimeAction(object sender, System.Timers.ElapsedEventArgs e)
        {
            Console.WriteLine("System.Timers.Timer {0:T}", e.SignalTime);
            Console.WriteLine("System.Timers.Timer event thread id {0}", Thread.CurrentThread.ManagedThreadId);
        }

执行结果如下

事件方法执行所在线程和调用线程并不一样

三、System.Windows.Forms,System.Web.UI,System.Windows.Threading

这些timer的执行方法所在的线程和调用线程一致

 

posted @ 2017-10-30 13:53  beautifulday  阅读(304)  评论(0编辑  收藏  举报