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.