ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

TimesOrUntil

Attempts to retrieve a valid a result from your function one or more times with an optional 'in between' step (i.e. delay). Replaces a common code pattern with a more readable, shared pattern.

Source

public static T TimesOrUntil<T>(this int times, Func<T> retrieve, Func<T, bool> validate, Action inbetween = null)
{
    T state;
    var count = 0;

    while (true)
    {
        state = retrieve();

        if (validate(state) || ++count >= times)
            break;

        if (inbetween != null) inbetween();
    }

    return state;
}

Example

var folderStatus = 5.TimesOrUntil(
imap.SelectInbox,
state => state.Recent > 0,
() => Thread.Sleep(500));

Author: James White

Submitted on: 29 okt. 2010

Language: C#

Type: System.Int32

Views: 4793