0

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; } 
3
  • You can only break from loops. So no. Commented Oct 17, 2022 at 10:54
  • Is there multithreading involved here? Commented Oct 17, 2022 at 10:55
  • 1
    It's not possible. BTW - Keep in mind that 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). Commented Oct 17, 2022 at 10:56

3 Answers 3

4

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. } 
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

This is not possible but if you want a other methode you could do this

void Run() { while (true) { if(Stop()) break; } } bool Stop() { //some calculation that returns true if the loop needs to break } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.