在c#中创建时间事件

时间:2012-09-17 18:19:51

标签: c# events timer

我正在尝试创建一个在一定时间内发生变化时执行函数的事件。计时器由另一个代码完成,它应该调用Plus(1),但是会改变所有计时器(如果我创建多个)?而且这段代码实际上并没有起作用。

namespace @event
{
    class Program
    {
        static void Main(string[] args)
        {
            Tick tijd = new Tick();
            tijd.interval = 10;
            tijd.TijdVeranderd += new EventHandler(Uitvoeren);
            dynamic func = new Tick();

            for (int i = 0; i < 100; i++)
            {
                func.Plus(1);
            }

            Console.ReadLine();
        }

        static void Uitvoeren(object sender, EventArgs e)
        {
            Console.WriteLine("Uitgevoerd!");
        }
    }

    public class Tick
    {
        public event EventHandler TijdVeranderd;

        public int interval;

        private int tijd;

        public void Plus(int i)
        {
            tijd += 1;
        }

        public int Verander
        {
            get { return this.tijd; }
            set
            {
                this.tijd = value;

                if (tijd == interval)
                {
                    if (this.TijdVeranderd != null)
                        this.TijdVeranderd(this, new EventArgs());

                    tijd = 0;
                }
            }
        }

        public Tick() { }
    }
}

编辑:我不想使用.net计时器,我想创建自己的。

4 个答案:

答案 0 :(得分:1)

只需使用.net计时器:

        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
        aTimer.Interval = 1000;   //here you can set your interval
        aTimer.Start();

您可以在这里捕捉事件并调用其他方法:

    void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //TODO: call your method like "Plus"
    }

答案 1 :(得分:1)

您的代码中似乎存在一些错误:

首先,在Main中,您在Plus()的不同实例上调用Tick而不是您配置的tijd.Plus(1)实例。尝试使用func.Plus(1)代替Plus

此外,在tijd的实现中,当您增加私有变量Verander时,与属性Verander关联的代码不会被执行,因此不会触发任何事件。要快速修复,请增加tijd而不是namespace @event { class Program { static void Main(string[] args) { Tick tijd = new Tick(); tijd.interval = 10; tijd.TijdVeranderd += new EventHandler(Uitvoeren); for (int i = 0; i < 100; i++) { tijd.Plus(1); } Console.ReadLine(); } static void Uitvoeren(object sender, EventArgs e) { Console.WriteLine("Uitgevoerd!"); } } public class Tick { public event EventHandler TijdVeranderd; public int interval; private int tijd; public void Plus(int i) { Verander += 1; } public int Verander { get { return this.tijd; } set { this.tijd = value; if (tijd == interval) { if (this.TijdVeranderd != null) this.TijdVeranderd(this, new EventArgs()); tijd = 0; } } } public Tick() { } } }

{{1}}

答案 2 :(得分:0)

您可以尝试使用此代码

private static System.Timers.Timer aTimer;

public static void Main()
    {

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }

答案 3 :(得分:0)

我不知道你为什么不使用系统计时器,但是这里有一个[未经测试的]计时器实现应该可以解决这个问题:

class MyCrudeTimer : IDisposable
{
    public event EventHandler Alarm ;

    public TimeSpan Duration           { get ; private set ; }
    public bool     AutomaticallyReset { get ; private set ; }
    public bool     IsRunning          { get ; private set ; }

    private Thread           timerThread ;
    private ManualResetEvent start       ;

    private void TimerCore()
    {
        try
        {
            while ( start.WaitOne() )
            {
                System.Threading.Thread.Sleep( Duration ) ;
                Alarm( this , new EventArgs() ) ;
            }
        }
        catch ( ThreadAbortException )
        {
        }
        catch ( ThreadInterruptedException )
        {
        }
        return ;
    }

    public MyCrudeTimer( TimeSpan duration , bool autoReset )
    {
        if ( duration <= TimeSpan.Zero ) throw new ArgumentOutOfRangeException("duration must be positive","duration") ;

        this.Duration            = duration  ;
        this.AutomaticallyReset  = autoReset ;
        this.start               = new ManualResetEvent(false) ;

        this.timerThread         = new Thread( TimerCore ) ;
        this.timerThread.Start() ;

        return ;
    }

    public void Start()
    {
        if ( IsRunning ) throw new InvalidOperationException() ;
        IsRunning = true ;
        start.Set() ;
        return ;
    }

    public void Stop()
    {
        if ( !IsRunning ) throw new InvalidOperationException() ;
        IsRunning = false ;
        start.Reset() ;
        return ;
    }

    public void Dispose()
    {
        try
        {
            if ( this.timerThread != null )
            {
                this.timerThread.Abort() ;
                this.timerThread = null ;
            }
        }
        catch
        {
        }
        return ;
    }
}