Search code examples
c#loopswhile-loopbreakanonymous-methods

Why can't I use break in a while loop in an anonymous method?


Why can't I use a break; statement in a while loop, whilst in an anonymous method?

I was working on the piece of code (below), when I got this error: "Control cannot leave the body of an anonymous method or lambda expression".

Thankfully I can solve the problem by using return; instead, but I'd still like to know why I can't use break;. To me, the main difference between the two statements, was that return; exits a method, and break; exits the further-most nested loop.

My code,

while (someCondition)
{
    System.Threading.Thread.Sleep(500);

    Application.Current.Dispatcher.Invoke(new Action(() =>
    {
        if (someOtherCondition)
        {
            // Do stuff...
        }
        else
        {
            if (anotherCondition)
            {
                break;
            }

            // Do something else...
        }
    }));
}

Solution

  • Rewriting the code helps to explain why:

    while (someCondition)
    {
        System.Threading.Thread.Sleep(500);
    
        Application.Current.Dispatcher.Invoke(MyMethod);
    }
    
    private void MyMethod()
    {
        if (someOtherCondition)
        {
            // Do stuff...
        }
        else
        {
            if (anotherCondition)
            {
                break;
            }
    
            // Do something else...
        }
    }
    

    You are breaking inside a function that has no loop. The loop exists in another method. So return needs to be called instead, as you found out. Just because you are using an annonymous method, it's still a separate method to the one containing the while loop.