Infinite Loop in Event

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 checked whether the Dot class timeout event occurred with the following code:

_TrateTimeOut += new Dta._TimeOutEventHandler(EncerraPorTimeOut);

However, when the method closesPorTimeOut is called it goes into an infinite loop.

private void EncerraPorTimeOut(){
   Console.WriteLine("Metodo Encerrado por TimeOut");
}
    
asked by anonymous 10.06.2014 / 21:50

2 answers

1

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

In CheckTimeOut , if you set that TimeOut.AutoReset = false; the handler of Elapsed will be called only the first time your timeout event occurs.

    
11.07.2014 / 04:44
0

This code is very funny. The correct would be to fire Timer with Enabled , and Elapsed to receive Handler typed, in this case, ElapsedEventHandler , like this:

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 looks like this:

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