C#定时器的使用

来源:互联网 发布:yy隐身软件 编辑:程序博客网 时间:2024/05/16 05:39

在C#里关于定时器类就有3个:  
1.定义在System.Windows.Forms里  
2.定义在System.Threading.Timer类里  
3.定义在System.Timers.Timer类里 

System.Windows.Forms.Timer是应用于WinForm中的,它是通过Windows消息机制实现的。它的主要缺点是计时不精确,而且必须有消息循环,控制台应用程序无法使用,它通过Tick属性来触发事件。  
 
System.Timers.Timer和System.Threading.Timer非常类似,它们是通过.NET  Thread  Pool实现的,轻量,计时精确,对应用程序、消息没有特别的要求。System.Timers.Timer还可以应用于WinForm,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码,它通过Elapsed属性来触发事件。

using System.Timers;
……
         private static int i = 0;
        static void Main(string[] args)
        {
            //for (int i = 0; i < 10; i++)
            //{
            //    Console.WriteLine(i);
            //    System.Threading.Thread.Sleep(1000);
            //}
            //Console.Read();
            System.Timers.Timer mytimer = new System.Timers.Timer();
            mytimer.Elapsed += new System.Timers.ElapsedEventHandler(handlemytimer);
            mytimer.Interval = 1000;
            mytimer.AutoReset = true;
            mytimer.Enabled = true;
            Console.Read();
        }

        private static void handlemytimer(object source, ElapsedEventArgs e)
            {               
                Console.WriteLine(i++);
            }

 

using System.Windows.Froms;
……
        private Timer mytimer = new Timer();
        private static int myx1 = 50;

        private void button1_Click(object sender, EventArgs e)
        {                      
            mytimer.Tick += new EventHandler(mytimer_Tick);
            mytimer.Interval = 500;
            mytimer.Start();
        }

        private void mytimer_Tick(Object myObject, EventArgs myEventArgs)
        {
            Graphics grfx = this.CreateGraphics();
            Pen mypen = new Pen(Color.Green);
            grfx.DrawLine(mypen, myx1, 200, myx1, 400);
            myx1 += 10;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            mytimer.Stop();
        }

 

原创粉丝点击