GugaMelkadze GugaMelkadze - 3 months ago 33
C# Question

Why does Thread.Sleep() freeze the Form?

I try to experiment with

Thread.Sleep()
. I created basic Windows Forms application with one button.

private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(DoStuff);
thread1.Start();

for (int i = 0; i < 100000; i++)
{
Thread.Sleep(500);
button1.Text +=".";
}
}

public void DoStuff()
{
//DoStuff
}


When I click my button the
DoStuff
method works fine, but the GUI freezes and nothing happens. Can someone explain me why?

Answer

To keep the UI active, you need for the main UI thread to service its message pump. It can only do that when it is not handling UI events. In your case the function

private void button1_Click(object sender, EventArgs e)
{
    Thread thread1 = new Thread(DoStuff);
    thread1.Start();

    for (int i = 0; i < 100000; i++)
    {
        Thread.Sleep(500);
        button1.Text +=".";
    }
}

does not return for around 100000*500 milliseconds. While this event handler is executing, the UI thread is busy. It is executing this event handler. As such it is not able to service the message pump. Hence your application's UI freezes.

Comments