Is it possible to call a method witch can break a loop from where it was called?
For example:
void Run() { while (true) { Stop(); } } void Stop() { break; } No, break is a statement and has to appear directly inside a loop (that's how the syntax defines it. If it appears without an enclosing loop, you get a syntax error).
It cannot be used from within a method to break out of an outer loop. However, you can change the method to return a bool instead:
void Run() { while (true) { if (Stop()) { break; } } } bool Stop() { return true; // return true or false, depending on whether you'd like to break out of the loop. } That's not possible directly. But you can use a method that returns a bool to indicate if the loop should be canceled (shown in other answers). Another way is to use a CancellationTokenSource which can be used in threads or tasks but even in a synchronous loop:
void Run(CancellationTokenSource cancelToken) { while (true) { if (cancelToken.IsCancellationRequested) break; Console.WriteLine("Still working..."); Thread.Sleep(500); } } Demo:
var cts = new CancellationTokenSource(); // cancel it after 3 seconds, just for demo purposes cts.CancelAfter(3000); Program p = new Program(); p.Run(cts); Console.WriteLine("Finished."); This breaks the loop after 3 seconds. If you want to break after a certain condition you can call the Cancel method.
Stop()can be called from other parts of your code, that do not even contain a loop (and the MSIL code for it would have to somehow manage both).