Search code examples
c#loopsmethodsbreak

Calling Break Method


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;
    }

Solution

  • 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.