TimesOrUntil

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

Description

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.

Details

Double click on the code to select all.

 

;