Question

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.

Was it helpful?

Solution

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!";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top