How to stop execution of a method from a delegate passed to it and execute it

I am trying to write a method that a delegate receives and performs this delegation in a loop. It is not very difficult, for example:

public static void RunInLoop<T>(IEnumerable<T> someCollection, 
                                 Action<T> action)
{           
        foreach (var item in someCollection)
        {
                action(item);
        }
}

However, let's say I would like to give the user a RunInLoopmeans to execute something like break, that is, stop the execution of the loop (or just just return from RunInLoop).

What I was thinking about:

  • Writing a method called Break()- which throws an exception (private), and then surrounds action(item)with a try catch, and if I catch my (private) exception - just come back. It is not so good if the delegate went through the catches Exception.

  • foreach Break(), . (, Silverlight), .

  • , , , . , , break . .

. /?

+3
2
public static void RunInLoop<T>(IEnumerable<T> someCollection, 
                                 Func<T, bool> action)
{           
        foreach (var item in someCollection)
        {
                if(action(item))
                     break;
        }
}

"" ( func, ) , , .

, - ForEach. - , , ( ).

+3

static/member, bool.

Action
{
    ...
    foreach
        if (!s_KeepGoing)
            break
    ...
}

, , bool, Action ref bool bool, .

public delegate void MyDelegate<in T>(T type, ref bool keepGoing);

public static void RunInLoop<T>(IEnumerable<T> someCollection, 
                                 MyDelegate<T> action)
{           
        foreach (var item in someCollection)
        {
                action(item, ref s_AnotherKeepGoing);
        }
}
0

All Articles