Infinite Loop in Event

Asked

Viewed 669 times

0

I have a class called Dta that contains the following code:

public event Dta._TimeOutEventHandler _TimeOut;

public delegate void _TimeOutEventHandler(Dta dta);


public void CheckTimeOut()
{
    if (TimeOut == null) {
        TimeOut = new Timers.Timer();
        TimeOut.Interval = 10000;
        TimeOut.Start();
        TimeOut.Elapsed += TrateTimeOut;
    } else {
        TimeOut.Stop();
        TimeOut.Start();

    }

}

private void TimeOut()
{
    TimeOut.Stop();
    if (_TimeOut != null) {
        _TimeOut(this);
    }
}

In another class called Monitor, I check if the timeout event of the Dta class occurred with the following code:

_TrateTimeOut += new Dta._TimeOutEventHandler(EncerraPorTimeOut);

However when the Encerraportimeout method is called it enters an infinite loop.

private void EncerraPorTimeOut(){
   Console.WriteLine("Metodo Encerrado por TimeOut");
}
  • 1

    You can also put the method EncerraPorTimeOut in your question?

2 answers

1

With infinite loop you mean that the Timer event is fired multiple times and you want it to be fired only one?

In CheckTimeOut, it is defined that TimeOut.AutoReset = false; the Handler of Elapsed will be called only the first time your timeout event happens.

0

It’s weird this code. The correct thing would be to fire the Timer with Enabled, and Elapsed receive a Handler typical, in this case, ElapsedEventHandler, thus:

public event ElapsedEventHandler Elapsed;

public void CheckTimeOut()
{
    if (TimeOut == null) 
    {
        TimeOut = new Timers.Timer();
        TimeOut.Interval = 10000;
        TimeOut.Elapsed += Elapsed;
        TimeOut.Enabled = true;
    } else 
    {
        TimeOut.Stop();
        TimeOut.Start();

    }
}

In Monitor:

Elapsed += new ElapsedEventHandler(EncerraPorTimeOut);

And EncerraPorTimeOut gets like this:

private static void ElapsedEventHandler(object source, ElapsedEventArgs e)
{
    Console.WriteLine("Metodo Encerrado por TimeOut");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.