且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#计时器组件的创建

更新时间:2023-11-17 15:56:16

如果要使用计时器,则应仅使用现有的计时器之一(System.Windows.Forms.Timer或System.Threading.计时器).您的组件没有意义,完全没有必要.
If you want a timer, you should just use one of the existing timers (System.Windows.Forms.Timer or System.Threading.Timer). Your component doesn''t make sense and is completely unnecessary.


using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.ComponentModel;
namespace timerer
{
    public class timercomp:Component
    {
        public int count=0;
 
        System.Timers.Timer myTimer = new System.Timers.Timer();
 
        public timercomp(IContainer container)
        {
            container.Add(this);
            myTimer.Elapsed += new ElapsedEventHandler(OnTimer);
        }
        
        public int start()
        {
 
                myTimer.Enabled = true;
                 myTimer.Interval += 1000;
                 myTimer.AutoReset = true;
                 return count;
        }
        
        public void OnTimer(Object source, ElapsedEventArgs e)
        {
            myTimer.Enabled = false;
            myTimer.Interval += 1000;
            count = count + 1;
            start();
 
        }
 
    }
}

//somewhere in your code you need
timercomp comp = new timercomp();
timercomp.start();



不知道为什么要在开始时返回count,当在上面的代码之外调用count时,它总是返回0.不过,应该使用调试器看到它​​递增.
请注意,您的间隔越来越大,不知道这是否是您的意图.



don''t know why you return count in start, when it is called outside the code above it will always return 0. You should see it incrementing using the debugger though.
Note your intervals are getting bigger and bigger, don''t know if that was your intention.