Share via


Form hangs while loop infinitely

Question

Thursday, December 15, 2011 1:10 PM

I have a form "form1.cs" where when I click a button "button_start", it will loop infinitely. My problem is, i  have a button "button_stop" which will break the loop. However, after I clicked  the start button, the form hangs and I could not click the stop button as the form is not responsive. How do I get around this? Thank you.

All replies (5)

Thursday, December 15, 2011 1:15 PM ✅Answered | 1 vote

Hello!

This is because you are using your GUI-thread in the loop, therefor you cant click the stopbutton. If you start the loop in a different thread. Your GUI-thread will still be available.

For example you can solve it like this.

            Task t = new Task(() =>
            {
                //loop
            });
            t.Start();

Keep in mind that if you access objects from both within your loop and from the GUI you need to be threadsafe : )

If my post is helpful. Please mark it as such : )


Thursday, December 15, 2011 1:18 PM ✅Answered | 2 votes

An infinite loop uses 100% of a CPU core and does nothing but generate heat.  If you don't need the heat you don't need the loop.

Rewrite your program to be event driven.   If you absolutely must poll something, use a timer.


Thursday, December 15, 2011 1:28 PM ✅Answered

Drop a BackgroundWorker on the form and use it to do the work in the background.

Consult the Microsoft Documentation for details.


Thursday, December 15, 2011 1:59 PM ✅Answered | 1 vote

Best to use Backgroundworker or a timer.

But, if you insist doing it a simple loop use:

while (true)
{
       // Your infinite code
       System.Threading.Thread.Sleep(1);
}

The Thread.Sleep will prevent your form from being hanged.

 

Noam B.

Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...


Monday, December 19, 2011 7:56 AM

The Thread.Sleep will prevent your form from being hanged.

It won't prevent that. If the UI thread is sleeping, the form won't be responsive and won't refresh.