0

I'm building a program that has 5 total forms. 1 MDIContainer and 4 MDIChildren.

I currently have a thread.sleep(1000) for each MDIChild. When the operation is performed, I still need the other 3 MDIChilds to be working and interactable. However, right now when the thread.sleep(1000) is called, the entire program sleeps for 1 second and I have to wait for the sleep to finish before interacting with any other form.

Is there a way to make a single form sleep? If so, how and example please.

user1760784
  • 119
  • 3
  • 12
  • 2
    Making your UI fall asleep makes very little sense in general. Set the form's Enabled property to false. Use a one second timer to set it back to true. – Hans Passant Dec 07 '12 at 20:35
  • thread.sleep(1000) is used to delay a process. In this particular program, it makes a picturebox change pictures for 1 second, and then change back. I don't want the form interactable during this 1 second, hence the sleep. – user1760784 Dec 07 '12 at 20:40

1 Answers1

1

You should basically never be sleeping in the UI thread...ever...for exactly the reason your question demonstrates.

You just want to execute some code in 1 second. There are two effective ways at doing this:

1) You can use a Timer. By using the timer in the Forms namespace you can ensure that it's Tick event fires in the UI thread, and you don't need to do anything special to interact with UI elements.

private void Form1_Load(object sender, EventArgs e)
{
    label1.Text = "Loading . . .";

    var timer = new System.Windows.Forms.Timer();
    timer.Interval = 1000;

    timer.Tick += (s, args) =>
    {
        label1.Text = "Done!";
    };

    timer.Start();
}

As you can see, this does take a bit more code than is ideal, but it still works.

2) If you have .NET 4.5 and C# 5.0 you can use tasks with await to make this really slick and easy:

private async void Form1_Load(object sender, EventArgs e)
{
    label1.Text = "Loading . . .";
    await Task.Delay(1000); //wait 1 second, but don't block the UI thread.
    label1.Text = "Done!";
}
Servy
  • 202,030
  • 26
  • 332
  • 449
  • I've always hated timers, but your example is very short, simple, and sweet. However, knowing about the await / delay was a pleasant surprise. THIS FEATURE IS AWESOME! plain and simple, thank you. – user1760784 Dec 07 '12 at 21:02
  • Note that the second example will, under the hood, result in code that looks very similar to the first example, it's just that you're getting the compiler and .NET library to do most of the work for you. – Servy Dec 07 '12 at 21:04