0

I have a class that uses a timer. A start method, to configure the timer and start it. And a Stop timer to dispose the timer. The code is this:

Start()
{
    _timer = new Timer(MyHandler, null, 0, 1000);
}

Stop()
{
    _timer.Dispose();
}


async void MyHandler()
{
    try
    {
        //Do something.
        await myAsyncMethd();
    }
    catch
    {
        Stop();
    }
}

The problem is that if some exception is catch in the handler, when it stop, the code of the handler still runs few more times until finally it stops.

I am wondering if this is normal because it is a code that it is run in another thread or there would be some way to stop immediately onece the exception is catched.

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193

2 Answers2

2

This is a "feature" of the Timer. The callback may run on a different thread and it does not even need to terminate before it is called again (for example if its execution takes more that 1000 ms). If you don't need this feature and it is OK to run the callback 1000 ms after the termination of the previous callback you can just avoid passing the period parameter and restart the timer manually at the end of the callback.

fog
  • 3,266
  • 1
  • 25
  • 31
1

You could use a private variable within the class to track whether the code should execute or not. Set it to true before starting the timer and then set it to false if the exception is thrown. Then in your handler check to see if the value is try before calling the code.

newky2k
  • 419
  • 5
  • 12