Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Sleep(300) not working correctly

I want it to execute the first part of the code, then make the pictureBox visible, pause for 3 seconds, hide the pictureBox and execute the rest of the code:

// first part of the code here
pb_elvisSherlock.Visible = true;
Thread.Sleep(300);
pb_elvisSherlock.Visible = false;
// rest of the code here

But it executes the whole block of code and only then pauses. Any ideas what to do?

Thanks!

like image 493
Rob Avatar asked Aug 07 '26 00:08

Rob


1 Answers

If you are trying to make a PictureBox appear for 3 seconds, you probably want your application to remain responsive during this time. So using Thread.Sleep is not a good idea because your GUI thread does not process messages while sleeping.

A better alternative would be to set a System.Windows.Forms.Timer for 3000 ms, to hide the PictureBox after 3 seconds without blocking your GUI.

For example, like this:

pb.Visible = true;
var timer = new Timer();
timer.Tick += () => { pb.Visible = false; timer.Stop(); };
timer.Interval = 3000;
timer.Start();
like image 77
YoG Avatar answered Aug 09 '26 14:08

YoG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!