简体   繁体   English

为什么 Thread.Sleep 会堆积?

[英]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.我想隐藏我的表单,将表单暂停 5.5 秒,然后再次显示。 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.我注意到的是,如果我在启动应用程序后第一次按下按钮 Thread.Sleep 是 5.5 秒,但如果我再次按下它,它会休眠 11 秒。 After I pressed it a third time it sleeps for 16 seconds and so on...在我第三次按下它后它会休眠 16 秒等等......

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.注意:我的应用程序迫切需要 Thread.Sleep。

    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();
        }

It is delegate subscriptions that stack up, ie 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.基本上只做一次。

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;您不会在任何地方取消订阅Timer.Tick事件,因此每次在此行中添加其他处理程序时都按下按钮timer.Tick += timer1_Tick_1; . . You should use timer.Tick -= timer1_Tick_1;你应该使用timer.Tick -= timer1_Tick_1; somewhere in your code在你的代码中的某个地方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM