Pass bool Foo (params []) as an argument method

There are times when a method needs to be run several times until it checks. In my case, there are expressions of the type bar.Name.Equals("John Doe")that I want to start and run until this expression is checked.

Sort of:

bool succeeded = TryUntillOk(bar.Name.Equals("John Doe"), 15, 100);

where there TryUntillOkwill be a method that starts this expression 15 times with a sleep of 100 ms between each call.

I read this excellent list of answers to similar problems, but in my case there is no standard delegate that TryUntillOkaccepted this method .

The title of the question is not constructive. Feel free to edit it :)

+5
source share
3 answers

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 will be called as follows:

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

, Func<bool>, , . Lambda .

+8

. @Jon lambda invoaction,

using System;
using System.Threading;

namespace test
{
    class something
    {
        public String Name;
    }

    class Program
    {
        private delegate bool TryableFunction(String s);

        private static bool TryUntillOk(TryableFunction f, String s, int howoften, int sleepms)
        {
            while (howoften-->0)
            {
                if (f(s)) return true;
                Thread.Sleep(sleepms);
            }
            return false;
        }

        static void Main(string[] args)
        {
            something bar=new something();

            bar.Name="Jane Doe";
            bool succeeded = TryUntillOk(bar.Name.Equals,"John Doe", 15, 100);
            Console.WriteLine("Succeeded with '{0}': {1}",bar.Name,succeeded);

            bar.Name="John Doe";
            succeeded = TryUntillOk(bar.Name.Equals,"John Doe", 15, 100);
            Console.WriteLine("Succeeded with '{0}': {1}",bar.Name,succeeded);
        }


    }
}
+1

You can check it out

delegate void d_name(string s);

d_name obj =new d_name(bar.Name.Equals);

bool succeeded = TryUntillOk(obj("John Doe"), 15, 100);

TryUntillOk(obj d,type parameter2,type parameter3 )
{
  //do your work
}  
0
source

All Articles