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

コードにいくつかのエラーがあるようです。

まず、で、構成したインスタンスとは異なるインスタンスをMain呼び出しています。の代わりに使用してみてください。Plus()Ticktijd.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

このコードで試すことができます

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

システム タイマーを使用しない理由はわかりませんが、[テストされていない] タイマーの実装を次に示します。

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 に答える