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!
If you are trying to make a
PictureBox
appear for 3 seconds, you probably want your application to remain responsive during this time. So usingThread.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 thePictureBox
after 3 seconds without blocking your GUI.For example, like this:
First of all you are only sleeping for 300 milliseconds not 3 seconds
Second your User interface will first be updated when your code is done executing, so you need to do something like this
I would try making this longer:
change to
You are only pausing for .3 seconds in your example (3000 = 3 seconds). If I had to guess, you aren't waiting long enough for the window to display. The code is actually working correctly.
Like the comment try adding in
Application.DoEvents();
after setting the visibility property.You can try this
Task.Delay(TimeSpan.FromSeconds(3)).Wait();
wherever Thread.Sleep method sometimes doesn't block the thread.The problem is that you are blocking the UI thread, which is the thread responsible for doing the redrawing of your form, so nothing gets redrawen during the 3 seconds you are waiting (Try draging your form around during these 3 seconds and you'll see it's totally unresponsive).
There are loads of ways of dealing with this, but the basic premise is that firstly you need to do your waiting on a background thread so your UI thread remains responsive (Options include using a BackgroundWorker, a Timer, the ThreadPool, a Thread or the TPL TaskFactory). Secondly, you must remember that any update to the UI must be done on the UI thread, so you must switch back to your UI thread (Using .Invoke() or a TaskScheduler) before you hide the picture box at the end.
This example uses the TPL (Task Parallel Library):
Extensions are quite helpful in such situations ;-)