The correct way to handle exiting an infinite loop in C #

In my applications, I find the need to have infinite loops, basically repeating a continuous action if another event does not occur, so I do this

while(chkFlag)
{
   //do something here which takes around 30 seconds
}

Then in some other case, say the button is pressed to stop the loop I'm doing

chkFlag = false;

Now this works, but the problem is that it does not stop the loop right away, since chkFlag is only checked after the complete loop has completed. So can someone please tell me how I can exit the instantaneouly cycle based on the event.

+3
source share
4 answers

"" , , - ( / ). BackgroundWorker (, ), .

BackgroundWorker (RunWorkerCompleted) ( ).

.


"" / ; , , .

+4

break;.

, downvoter, . , ( , , , continue , for - ).

break , .

, , break;, . BackgroundWorkers Cancel Tokens ( , ).

+1

(, Abort, ), if(!chkFlag) break; , . - BackgroundWorker CancellationToken, .

Of course, it will still need to be run in another thread so that the button event can be triggered at all. BackgroundWorker will take care of this automatically.

+1
source

Is it possible that you want to use the new thread? What do you do for 30 seconds in a loop. It looks like there might be a better design to use.

Have you considered using a timer or setting up an event handler?

0
source

All Articles