开发者

Cleaning Up Timers?

开发者 https://www.devze.com 2023-02-19 15:09 出处:网络
The following code hides a form for 10 seconds.Nothing too crazy. Each time the button is pressed, it creates a new timer object that doesn\'t stop and just keeps going.My intuition tells me that if

The following code hides a form for 10 seconds. Nothing too crazy. Each time the button is pressed, it creates a new timer object that doesn't stop and just keeps going. My intuition tells me that if you end up pressing this button many times, you'll have a bunch of timers that are running when only one is necessary (or is my assumption incorrect?). Also, if I do need to stop and dispose this timer, would I just send it as an argument in RevealForm or have the timer be a class level variable and just stop/reset it each time?

    private void ButtonHide_Click(object sender, EventArgs e) {
        this.Visible = false;
        System.Timers.Timer t = new System.Timers.Timer();
        t.Elapsed += new ElapsedEventHandler(RevealForm);
        t.Interval = 10000;
        t.AutoReset = false;
        t.Start();
    }

    private void RevealForm(object source, ElapsedEventArgs e) {
        InvokeReveal();
    }

    private void InvokeReveal() {
        if (InvokeRequired) {
            Invoke(new Action(InvokeReveal));
        }
        else {
       开发者_JAVA技巧     this.Visible = true;
        }
    }

Thanks much!


Create the timer in the class then call t.start() on each click.

No need to destroy/cleanup/etc. Just recycle the one you have.


Your assumption is correct - testing would have asserted such for you.

You could either:

  • A) Disable the timer after each execution (per-interval) and enable on click, or,

  • B) Stop and destroy the timer and create a new one with each click.

Either option will require a little refactoring of your existing code.

As for the second part of the question - how you stop the timer is preferential. in such a small application (if this is its function in entirety) then simply stopping the timer within the event handler (or related method) would just do the trick, though in order to access the Timer instance you would declare it at a higher level in scope (i.e not bound within the scope of the click event handler).


Generally, the first thing you do is stop the timer in your event handler.

If you just want one timer then make it a form level variable, start it in your ButtonHide_Click, then at the top of your RevealForm method, stop the timer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号