2

我正在尝试创建一个在一定时间更改时执行函数的事件。计时器由另一个代码完成,它应该调用 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

4 回答 4

2

只需像这样使用 .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"
    }
于 2012-09-17T18:25:34.340 回答
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);
    }
于 2012-09-17T18:26:38.800 回答
0

您的代码中似乎有几个错误:

首先,在 中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() { }
    }
}
于 2012-09-17T18:33:00.880 回答
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 ;
    }
}
于 2012-09-17T19:30:03.703 回答