Search code examples
c#timeoutpredicate

C# function that checks predicate


I'm coding a function that receives a condition to be met and a time out and it finishes when the condition is met or it times out.

This is what I have so far :

public static bool CheckWithTimeout(bool toBeChecked, int msToWait)
{
    //var src = CancellationSource
    var task = Task.Run(()=> {
        while (!toBeChecked)
        {
            System.Threading.Thread.Sleep(25);
        }                    
    });
    if (task.Wait(TimeSpan.FromMilliseconds(msToWait)))
        return toBeChecked;
    else
        return false;
}

It works nice for simple bools but I would like to call it like:

CheckWithTimeout(myValue > 10, 500)

And it would return when myValue is bigger than ten, or 500 ms passed (and returns false in this case)

I checked and I think Func is what I need but.. I cannot find a proper example. Additionally, if there is an already existing method to achieve this I'd definitely prefer it.


Solution

  • It's better to use separate tasks for the result and the waiting.

        private async Task<bool> CheckWithTimeout(Func<bool> toBeChecked, int msToWait)
        {
            var waitTask = Task.Delay(msToWait);
            var checkTask = Task.Run(toBeChecked);
            await Task.WhenAny(waitTask, checkTask);
            return checkTask.IsCompleted && await checkTask;
        }
    
    
        private async Task<bool> CheckWithTimeout<T>(Predicate<T> toBeChecked, T predicateParameter, int msToWait)
        {
            var waitTask = Task.Delay(msToWait);            
            var checkTask = Task.Run(() => toBeChecked(predicateParameter));
            await Task.WhenAny(waitTask, checkTask);
            return checkTask.IsCompleted && await checkTask;
        }
    

    That way you do not nescessary have to wait for the timeout. (And Taks.Delay is better than Task.Wait because it doesn't block)

    Edit: Example with function or predicate