Home > database >  Calling Break Method
Calling Break Method

Time:10-17

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

CodePudding user response:

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

CodePudding user response:

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
}

CodePudding user response:

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.

  • Related