Pass a bool Foo(params[]) as method Argument

.net-3.5, c#, invoke

Solution

You are probably looking for something like this:

bool TryRepeatedly(Func<bool> condition, int maxRepeats, TimeSpan repeatInterval)
{
    for (var i = 0; i < maxRepeats; ++i)
    {
        if (condition()) return true;
        Thread.Sleep(repeatInterval); // or your choice of waiting mechanism
    }
    return false;
}

Which would be invoked as follows:

bool succeeded = TryRepeatedly(() => bar.Name.Equals("John Doe"),
                               15,
                               TimeSpan.FromMilliseconds(100));

The only interesting part here is that you specify the condition as a `Func<bool>`, which is a delegate to a method that takes no parameters and returns a boolean. Lambda expression syntax allows you to trivially construct such a delegate at the call site.

Problem

There are times that a method needs to be run several times until it validates. In my case there are expressions like `bar.Name.Equals("John Doe")` which I want to run and run until this expression validates. Something like: ``` bool succeeded = TryUntillOk(bar.Name.Equals("John Doe"), 15, 100); ``` where `TryUntillOk` would be a method that runs this expression 15 times with a sleep of 100ms between each call. I read this excellent list of answers to similar issues but in my case there is no standar delegate that this `TryUntillOk` method would accept. The title of the question is not constructive. Feel free to edit it :)

Original source

Related problems