az333332
az333332

Reputation: 35

Why does Thread.Sleep stacks up?

I have a button which activates a timer for one tick. I want to hide my form, pause the form for 5.5s and then show it again. What I have noticed is that if I press the button the first time after I started the application Thread.Sleep is 5.5s but if I press it again it sleeps for 11 seconds. After I pressed it a third time it sleeps for 16 seconds and so on...

This is really wierd for me and I'm not sure why it behaves that way. Someone has an idea?

Note: Thread.Sleep is desperately needed for my application.

    using System.Threading;

    private void Btn_Abwesend_Click(object sender, EventArgs e)
        {       
            timer.Tick += timer1_Tick_1;
            timer.Interval = 100;
            timer.Start();
        }

    private void timer1_Tick_1(object sender, EventArgs e)
        {
            this.Hide();
            Thread.Sleep(5500);
            this.Show();
            timer.Stop();
        }

Upvotes: 2

Views: 72

Answers (2)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23298

You don't unsubscribe from Timer.Tick event anywhere, so by pressing the button every time you add an additional handler in this line timer.Tick += timer1_Tick_1;. You should use timer.Tick -= timer1_Tick_1; somewhere in your code

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064064

It is delegate subscriptions that stack up, i.e. this

timer.Tick += timer1_Tick_1;

Every time you do that, it adds a handler. The fact that the same target instance/method are added each time doesn't matter: it will get invoked multiple times. Only do that once, basically.

Upvotes: 4

Related Questions