Search code examples
c#winformsmultithreadingsleep

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!


Solution

  • pb_elvisSherlock.Visible = true;
    Application.DoEvents(); //let the app show the picturebox
    Thread.Sleep(3000);
    pb_elvisSherlock.Visible = false;
    

    The problem is that you don't give the message loop a chance to display the picture box before you pause the GUI thread. Application.DoEvents() solve that.

    Note that using Thread.Sleep on the GUI thread will make the painting freeze (try move a window over your app when the Sleep is active).

    You should do something like this:

    pb_elvisSherlock.Visible = true;
    int counter = 0;
    while (counter < 30)
    {
      Application.DoEvents(); 
      Thread.Sleep(100);
      ++counter;
    }
    pb_elvisSherlock.Visible = false;
    

    It's still kind of a hack but the window will be redrawn and respond as it should.

    Update 2

    Well. DoEvents seems to be a bit to much of a hack. (thanks for the comments).

    If the picturebox is a kind of a nag screen do something like this:

    Alternative 1

    1. Create a new form containing only the picturebox (don't use a border on that form).
    2. Add a timer to that form that calls Close after three seconds
    3. Call 'myNagForm.DoModal()'

    That solution prevents your users from doing anything in your "normal" form while the nagform is visible.

    Alternative 2

    1. Create a background worker, see here for example: http://dotnetperls.com/backgroundworker
    2. Move your picturebox AND the code executed after it to the background worker method.