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