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