Home > database >  C# adding infinity loop in button click event and break it with another button click event
C# adding infinity loop in button click event and break it with another button click event

Time:10-20

I tried to make a while (work){....} inside button event called start to do some stuff like label changing in the same form with random values and I have another button called stop I want to make the work=false; so the while should be break


the problem is when I clicked start button and the form froze and did nothing how I can do that like stay in the while loop and access all other events

CodePudding user response:

As long as the loop runs, no events (like your other button's click) can be processed. This results in freezing the UI.

Better use a Timer instead of an infinite loop. The timer will not freeze the UI but call a Tick event at defined intervals and allow other events to be processed between two ticks. It is then easy for another button to stop this timer.

Since you have not mentioned any UI technology (is it WinForms, WPF, WebForms, MAUI, Xamarin, ...?) and not shown any code, it is difficult to give you example code.

  • Related