简体   繁体   中英

C# Timer.Elapsed Event firing twice consecutively

I have an application that calls static methods in a DLL every 60 seconds as part of a system "self-check" application. When I manually run the methods, they all complete in less than 10 seconds. My problem is the timer.elapsed event is firing twice, one right after the other. To add to that, for each time the timer elapses, the event fires one more time. (eg first time it's 2 firings, second it's 3, third it's 4, etc.) I have tried setting the timer.AutoReset = false along with setting timer.Enabled = false at the beginning of the elapsed event and then setting it to true at the end of the event. I've tried resetting the interval in the event. Every post I have found indicates that the above actions should have resolved this problem. Can anyone help me find what I'm missing?

static Timer cycle = new Timer();
static int cycCount = 0;
static void Main(string[] args)
{
    Console.WriteLine("Firebird Survivor Auto Cycle Started.");

    Console.CancelKeyPress += Console_CancelKeyPress;

    cycle.Interval = 60000; //set interval for service checks.
    cycle.Elapsed += new ElapsedEventHandler(CycleComplete_Elapsed);
    cycle.AutoReset = false;
    cycle.Enabled = true;

    cycle.Elapsed += CycleComplete_Elapsed; 

    while (1 == 1) //stop main method from completing indefinitely
    {
        //WAIT FOR TIMER TO ELAPSE
    }

}

private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    cycle = null;
}

static void CycleComplete_Elapsed(object sender, ElapsedEventArgs e) //method triggered by timer
{
    cycle.Enabled = false;

    cycCount++;

    WormholeServiceControls.CheckWormHoleStatus();
    TimeControls.CheckTimePl(); //call time check
    PegasusServiceControls.CheckPegasusStatus(null);

    Console.Clear();
    Console.WriteLine("--------------------------");
    Console.WriteLine(String.Format("| Successful Cycles: {0} |", cycCount));
    Console.WriteLine("--------------------------");

    cycle.Enabled = true;
}

It seems your problem comes from the event handling you are doing. You are assigning the Elapsed event more than one time:

cycle.Elapsed += new ElapsedEventHandler(CycleComplete_Elapsed);
cycle.Elapsed += CycleComplete_Elapsed; 

Why this two lines?. You will be all right with only this:

cycle.Elapsed += new ElapsedEventHandler(CycleComplete_Elapsed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM