.net construct for while loop with timeout

I don't know that there's any existing thing, but I would think you could create a method to that would accept the timeout and the success-determination function. Something like this:

public static bool KeepTrying(int timeout, Func<bool> operation)
{
    bool success = false;
    int elapsed = 0;
    while ((!success) && (elapsed < timeout))
    {
        Thread.Sleep(1000);
        elapsed += 1000;
        success = operation();
    }
    return success;
}

or maybe your Function could be more "robust" and you could couple it with flexible arguments:

public bool KeepTrying(int timeout, Func<object[], bool> operation, params object[] arguments)
{
    bool success = false;
    int elapsed = 0;
    while ((!success) && (elapsed < timeout))
    {
        Thread.Sleep(1000);
        elapsed += 1000;
        success = operation(arguments);
    }
    return success;
}

You really should not have to use Sleep() to wait for tasks to complete. You waste an average of 500ms after the task has completed by doing this.

You ought to be able to do this deterministically using Task Parallel Library, see here for example.

This example shows how to use the Wait method, or its equivalent in the Task class, to wait on a single task. It also shows how to use the static WaitAll and WaitAny methods to wait on multiple tasks.


You could wrap your algorithm in a method:

public bool RetryUntilSuccessOrTimeout(Func<bool> task, TimeSpan timeSpan)
{
    bool success = false;
    int elapsed = 0;
    while ((!success) && (elapsed < timeSpan.TotalMilliseconds))
    {
        Thread.Sleep(1000);
        elapsed += 1000;
        success = task();
    }
    return success;
}

and then:

if (RetryUntilSuccessOrTimeout(() => SomeTask(arg1, arg2), TimeSpan.FromSeconds(10)))
{
    // the task succeeded
}

You could use SpinWait.SpinUntil

See https://msdn.microsoft.com/en-us/library/dd449238(v=vs.110).aspx

bool spinUntil = System.Threading.SpinWait.SpinUntil(() => job.IsDisposed, TimeSpan.FromSeconds(5));