13

So I setup a System.Timers.Timer and have a handler for the Elapsed event. It works as expected.

However, if I want to debug the code that is called within the elapsed handler; the timer will continue generating additional events. Thus, I can't single step through the code because timer events stack up on top of each other.

The current workaround is to call Stop on the timer upon entering the handler and Start when leaving. However, that is not how the system is supposed to work so that is a temporary fix. I was wondering if there is a way to configure the debugger to halt the timer while debugging.

2 Answers 2

13

If you want you can wrap this into a #if DEBUG directive or you can use System.Diagnostics.Debugger.IsAttached.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 - For the Debugger.IsAttached property. I think I like that better than #if.
to be honest: that depends on what you want to achieve - with the #if thing you don't have the code in your release-version at all, where the other option will be a unused code-path there.
6

In your Timer.Elapsed event handler, maybe you can use some preprocessor directives to include code that stops and starts (or disables and enables) the timer:

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
#if DEBUG
        (source as Timer).Stop();
        // or
        (source as Timer).Enabled = false;
#endif

        // do your work

#if DEBUG
        (source as Timer).Start();
        // or
        (source as Timer).Enabled = true;
#endif
    }

1 Comment

I have the Stop and Start as a temporary workaround. I'm not really a fan of preprocessor directives. But if that is the only way that might be the route I take.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.